split LOGIN and LOGOUT from RECEIVE_ME

This commit is contained in:
HF 2020-11-28 01:11:08 +01:00
parent 46ba5188b5
commit ac464ba5a7
19 changed files with 155 additions and 132 deletions

View File

@ -483,39 +483,29 @@ export function receivePixelUpdate(
}; };
} }
export function loginUser(
me: Object,
): Action {
console.log('login', me);
return {
type: 'LOGIN',
...me,
};
}
export function receiveMe( export function receiveMe(
me: Object, me: Object,
): Action { ): Action {
const {
name,
messages,
mailreg,
totalPixels,
dailyTotalPixels,
ranking,
dailyRanking,
minecraftname,
blockDm,
canvases,
channels,
blocked,
userlvl,
} = me;
return { return {
type: 'RECEIVE_ME', type: 'RECEIVE_ME',
name: (name) || null, ...me,
messages: (messages) || [], };
mailreg: (mailreg) || false, }
totalPixels,
dailyTotalPixels, export function logoutUser(
ranking, ): Action {
dailyRanking, return {
minecraftname, type: 'LOGOUT',
blockDm: !!blockDm,
canvases,
channels,
blocked,
userlvl,
}; };
} }
@ -819,11 +809,9 @@ export function startDm(query): PromiseAction {
'OK', 'OK',
)); ));
} else { } else {
const cid = res[0]; const cid = Object.keys(res)[0];
if (cid) { dispatch(addChatChannel(res));
dispatch(addChatChannel(res)); dispatch(setChatChannel(cid));
dispatch(setChatChannel(cid));
}
} }
dispatch(setApiFetching(false)); dispatch(setApiFetching(false));
}; };

View File

@ -94,6 +94,23 @@ export type Action =
blocked: Array, blocked: Array,
userlvl: number, userlvl: number,
} }
| { type: 'LOGIN',
name: string,
waitSeconds: number,
messages: Array,
mailreg: boolean,
totalPixels: number,
dailyTotalPixels: number,
ranking: number,
dailyRanking: number,
minecraftname: string,
blockDm: boolean,
canvases: Object,
channels: Object,
blocked: Array,
userlvl: number,
}
| { type: 'LOGOUT' }
| { type: 'RECEIVE_STATS', totalRanking: Object, totalDailyRanking: Object } | { type: 'RECEIVE_STATS', totalRanking: Object, totalDailyRanking: Object }
| { type: 'SET_NAME', name: string } | { type: 'SET_NAME', name: string }
| { type: 'SET_MINECRAFT_NAME', minecraftname: string } | { type: 'SET_MINECRAFT_NAME', minecraftname: string }

View File

@ -4,8 +4,11 @@
*/ */
import React from 'react'; import React from 'react';
import { connect } from 'react-redux';
import { validatePassword, parseAPIresponse } from '../utils/validation'; import { validatePassword, parseAPIresponse } from '../utils/validation';
import { logoutUser } from '../actions';
function validate(password) { function validate(password) {
const errors = []; const errors = [];
@ -64,8 +67,8 @@ class DeleteAccount extends React.Component {
}); });
return; return;
} }
const { setName } = this.props; const { logout } = this.props;
setName(null); logout();
} }
render() { render() {
@ -94,4 +97,12 @@ class DeleteAccount extends React.Component {
} }
} }
export default DeleteAccount; function mapDispatchToProps(dispatch) {
return {
async logout() {
dispatch(logoutUser());
},
};
}
export default connect(null, mapDispatchToProps)(DeleteAccount);

View File

@ -3,9 +3,11 @@
* @flow * @flow
*/ */
import React from 'react'; import React from 'react';
import { connect } from 'react-redux';
import { import {
validateEMail, validateName, validatePassword, parseAPIresponse, validateEMail, validateName, validatePassword, parseAPIresponse,
} from '../utils/validation'; } from '../utils/validation';
import { loginUser } from '../actions';
function validate(nameoremail, password) { function validate(nameoremail, password) {
@ -60,7 +62,7 @@ class LogInForm extends React.Component {
e.preventDefault(); e.preventDefault();
const { nameoremail, password, submitting } = this.state; const { nameoremail, password, submitting } = this.state;
const { me: setMe } = this.props; const { login } = this.props;
if (submitting) return; if (submitting) return;
const errors = validate(nameoremail, password); const errors = validate(nameoremail, password);
@ -80,7 +82,7 @@ class LogInForm extends React.Component {
}); });
return; return;
} }
setMe(me); login(me);
} }
render() { render() {
@ -116,4 +118,12 @@ class LogInForm extends React.Component {
} }
} }
export default LogInForm; function mapDispatchToProps(dispatch) {
return {
login(me) {
dispatch(loginUser(me));
},
};
}
export default connect(null, mapDispatchToProps)(LogInForm);

View File

@ -9,7 +9,7 @@ import {
validateEMail, validateName, validatePassword, parseAPIresponse, validateEMail, validateName, validatePassword, parseAPIresponse,
} from '../utils/validation'; } from '../utils/validation';
import { showUserAreaModal, receiveMe } from '../actions'; import { showUserAreaModal, loginUser } from '../actions';
function validate(name, email, password, confirmPassword) { function validate(name, email, password, confirmPassword) {
@ -94,8 +94,8 @@ class SignUpForm extends React.Component {
}); });
return; return;
} }
const { doMe, userarea } = this.props; const { login, userarea } = this.props;
doMe(me); login(me);
userarea(); userarea();
} }
@ -163,8 +163,8 @@ class SignUpForm extends React.Component {
function mapDispatchToProps(dispatch) { function mapDispatchToProps(dispatch) {
return { return {
doMe(me) { login(me) {
dispatch(receiveMe(me)); dispatch(loginUser(me));
}, },
userarea() { userarea() {
dispatch(showUserAreaModal()); dispatch(showUserAreaModal());

View File

@ -14,6 +14,7 @@ import ChangeName from './ChangeName';
import ChangeMail from './ChangeMail'; import ChangeMail from './ChangeMail';
import DeleteAccount from './DeleteAccount'; import DeleteAccount from './DeleteAccount';
import SocialSettings from './SocialSettings'; import SocialSettings from './SocialSettings';
import { logoutUser } from '../actions';
import { numberToString } from '../core/utils'; import { numberToString } from '../core/utils';
@ -172,7 +173,6 @@ class UserArea extends React.Component {
{(deleteAccountExtended) {(deleteAccountExtended)
&& ( && (
<DeleteAccount <DeleteAccount
setName={setName}
done={() => { this.setState({ deleteAccountExtended: false }); }} done={() => { this.setState({ deleteAccountExtended: false }); }}
/> />
)} )}
@ -226,4 +226,18 @@ function mapStateToProps(state: State) {
return { name, mailreg, stats }; return { name, mailreg, stats };
} }
export default connect(mapStateToProps)(UserArea); function mapDispatchToProps(dispatch) {
return {
async logout() {
const response = await fetch(
'./api/auth/logout',
{ credentials: 'include' },
);
if (response.ok) {
dispatch(logoutUser());
}
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(UserArea);

View File

@ -10,7 +10,7 @@ import type { State } from '../reducers';
import { import {
showRegisterModal, showForgotPasswordModal, setName, setMailreg, receiveMe, showRegisterModal, showForgotPasswordModal, setName, setMailreg,
} from '../actions'; } from '../actions';
import LogInForm from './LogInForm'; import LogInForm from './LogInForm';
import Tabs from './Tabs'; import Tabs from './Tabs';
@ -87,8 +87,6 @@ const UserAreaModal = ({
name, name,
register, register,
forgotPassword, forgotPassword,
doMe,
logout,
setUserName, setUserName,
setUserMailreg, setUserMailreg,
userlvl, userlvl,
@ -99,14 +97,12 @@ const UserAreaModal = ({
<LogInArea <LogInArea
register={register} register={register}
forgotPassword={forgotPassword} forgotPassword={forgotPassword}
me={doMe}
/> />
) )
: ( : (
<Tabs> <Tabs>
<div label="Profile"> <div label="Profile">
<UserArea <UserArea
logout={logout}
setName={setUserName} setName={setUserName}
setMailreg={setUserMailreg} setMailreg={setUserMailreg}
/> />
@ -142,25 +138,12 @@ function mapDispatchToProps(dispatch) {
forgotPassword() { forgotPassword() {
dispatch(showForgotPasswordModal()); dispatch(showForgotPasswordModal());
}, },
doMe(me) {
dispatch(receiveMe(me));
},
setUserName(name) { setUserName(name) {
dispatch(setName(name)); dispatch(setName(name));
}, },
setUserMailreg(mailreg) { setUserMailreg(mailreg) {
dispatch(setMailreg(mailreg)); dispatch(setMailreg(mailreg));
}, },
async logout() {
const response = await fetch(
'./api/auth/logout',
{ credentials: 'include' },
);
if (response.ok) {
const resp = await response.json();
dispatch(receiveMe(resp.me));
}
},
}; };
} }

View File

@ -71,16 +71,6 @@ export const TILE_SIZE = 256;
// how much to scale for a new tiled zoomlevel // how much to scale for a new tiled zoomlevel
export const TILE_ZOOM_LEVEL = 4; export const TILE_ZOOM_LEVEL = 4;
// TODO get rid of those or use it myself
export const social = {
facebook: 'https://www.facebook.com/pixelplanetfun/',
reddit: 'https://reddit.com/r/PixelPlanetFun',
twitter: 'https://twitter.com/pixelplanetfun',
discord: 'https://pixelplanet.fun/discord',
telegram: 'https://telegram.me/pixelplanetfun',
youtube: 'https://www.youtube.com/c/PixelPlanetFun',
};
export const COOKIE_SESSION_NAME = 'pixelplanet.session'; export const COOKIE_SESSION_NAME = 'pixelplanet.session';
export const SECOND = 1000; export const SECOND = 1000;

View File

@ -137,7 +137,6 @@ export function getCellInsideChunk(
canvasSize: number, canvasSize: number,
pixel: Cell, pixel: Cell,
): Cell { ): Cell {
// TODO assert is positive!
return pixel.map((x) => mod(x + canvasSize / 2, TILE_SIZE)); return pixel.map((x) => mod(x + canvasSize / 2, TILE_SIZE));
} }

View File

@ -198,7 +198,18 @@ class User {
if (this.regUser == null) { if (this.regUser == null) {
return { return {
name: null, name: null,
mailVerified: false,
mcVerified: false,
minecraftname: null,
blockDm: false,
totalPixels: 0,
dailyTotalPixels: 0,
ranking: null,
dailyRanking: null,
mailreg: false,
userlvl: 0,
channels: this.channels, channels: this.channels,
blocked: this.blocked,
}; };
} }
const { regUser } = this; const { regUser } = this;

View File

@ -41,7 +41,8 @@ export default function chat(
action: Action, action: Action,
): ChatState { ): ChatState {
switch (action.type) { switch (action.type) {
case 'RECEIVE_ME': { case 'RECEIVE_ME':
case 'LOGIN': {
return { return {
...state, ...state,
channels: action.channels, channels: action.channels,
@ -49,6 +50,26 @@ export default function chat(
}; };
} }
case 'LOGOUT': {
const channels = { ...state.channels };
const messages = { ...state.messages };
const keys = Object.keys(channels);
for (let i = 0; i < messages.length; i += 1) {
const cid = keys[i];
if (channels[cid][1] === 0) {
delete messages[cid];
delete channels[cid];
}
}
return {
...state,
inputMessage: '',
channels,
blocked: [],
messages,
};
}
case 'BLOCK_USER': { case 'BLOCK_USER': {
const { userId, userName } = action; const { userId, userName } = action;
const blocked = [ const blocked = [
@ -88,6 +109,7 @@ export default function chat(
case 'ADD_CHAT_CHANNEL': { case 'ADD_CHAT_CHANNEL': {
const { channel } = action; const { channel } = action;
console.log('adding channel', channel);
return { return {
...state, ...state,
channels: { channels: {

View File

@ -145,7 +145,8 @@ export default function gui(
}; };
} }
case 'RECEIVE_ME': { case 'RECEIVE_ME':
case 'LOGIN': {
const { channels } = action; const { channels } = action;
const cids = Object.keys(channels); const cids = Object.keys(channels);
const chatRead = { ...state.chatRead }; const chatRead = { ...state.chatRead };

View File

@ -49,12 +49,10 @@ export default function modal(
}; };
} }
case 'RECEIVE_ME': { case 'LOGOUT': {
const { name } = action;
const chatOpen = (name) ? state.chatOpen : false;
return { return {
...state, ...state,
chatOpen, chatOpen: false,
}; };
} }

View File

@ -139,7 +139,8 @@ export default function user(
}; };
} }
case 'RECEIVE_ME': { case 'RECEIVE_ME':
case 'LOGIN': {
const { const {
name, name,
mailreg, mailreg,
@ -169,6 +170,19 @@ export default function user(
}; };
} }
case 'LOGOUT': {
return {
...state,
name: null,
messages: [],
mailreg: false,
minecraftname: null,
blockDm: false,
userlvl: 0,
nameRegExp: null,
};
}
case 'RECEIVE_STATS': { case 'RECEIVE_STATS': {
const { totalRanking, totalDailyRanking } = action; const { totalRanking, totalDailyRanking } = action;
return { return {

View File

@ -4,9 +4,6 @@
*/ */
import type { Request, Response } from 'express'; import type { Request, Response } from 'express';
import getMe from '../../../core/me';
import chatProvider from '../../../core/ChatProvider';
export default async (req: Request, res: Response) => { export default async (req: Request, res: Response) => {
const { user } = req; const { user } = req;
if (!user) { if (!user) {
@ -17,16 +14,9 @@ export default async (req: Request, res: Response) => {
return; return;
} }
const me = await getMe(user);
req.logout(); req.logout();
res.status(200); res.status(200);
res.json({ res.json({
success: true, success: true,
me: {
name: null,
waitSeconds: me.waitSeconds,
canvases: me.canvases,
channels: chatProvider.defaultChannels,
},
}); });
}; };

View File

@ -98,7 +98,6 @@ async function block(req: Request, res: Response) {
dmu2id = userId; dmu2id = userId;
} }
// TODO test if this removes association too
const channel = await Channel.findOne({ const channel = await Channel.findOne({
where: { where: {
type: 1, type: 1,

View File

@ -23,7 +23,6 @@ const chunks = [];
class ProtocolClient extends EventEmitter { class ProtocolClient extends EventEmitter {
url: string; url: string;
ws: WebSocket; ws: WebSocket;
name: string;
canvasId: number; canvasId: number;
channelId: number; channelId: number;
timeConnected: number; timeConnected: number;
@ -37,7 +36,6 @@ class ProtocolClient extends EventEmitter {
this.isConnecting = false; this.isConnecting = false;
this.isConnected = false; this.isConnected = false;
this.ws = null; this.ws = null;
this.name = null;
this.canvasId = '0'; this.canvasId = '0';
this.channelId = 0; this.channelId = 0;
this.msgQueue = []; this.msgQueue = [];
@ -96,14 +94,6 @@ class ProtocolClient extends EventEmitter {
this.ws.close(); this.ws.close();
} }
setName(name) {
if (this.isConnected && this.name !== name) {
console.log('Name change requieres WebSocket restart');
this.name = name;
this.reconnect();
}
}
setCanvas(canvasId) { setCanvas(canvasId) {
/* canvasId can be string or integer, thanks to /* canvasId can be string or integer, thanks to
* JSON not allowing integer keys * JSON not allowing integer keys
@ -181,13 +171,11 @@ class ProtocolClient extends EventEmitter {
// signal // signal
const [signal, args] = data; const [signal, args] = data;
this.emit(signal, args); this.emit(signal, args);
break;
} }
default: default:
// nothing // nothing
} }
} else {
// string = name
this.name = data;
} }
} }

View File

@ -88,10 +88,6 @@ class SocketServer extends WebSocketEvents {
ws.rateLimiter = new RateLimiter(20, 15, true); ws.rateLimiter = new RateLimiter(20, 15, true);
cheapDetector(user.ip); cheapDetector(user.ip);
if (ws.name) {
ws.send(`"${ws.name}"`);
}
ws.send(OnlineCounter.dehydrate({ ws.send(OnlineCounter.dehydrate({
online: this.wss.clients.size || 0, online: this.wss.clients.size || 0,
})); }));
@ -337,16 +333,17 @@ class SocketServer extends WebSocketEvents {
*/ */
const dmUserId = chatProvider.checkIfDm(user, channelId); const dmUserId = chatProvider.checkIfDm(user, channelId);
if (dmUserId) { if (dmUserId) {
console.log('is dm');
const dmWs = this.findWsByUserId(dmUserId); const dmWs = this.findWsByUserId(dmUserId);
if (dmWs) { if (!dmWs
const { user: dmUser } = dmWs; || !chatProvider.userHasChannelAccess(dmWs.user, channelId)
if (!dmUser || !dmUser.userHasChannelAccess(channelId)) { ) {
ChatProvider.addUserToChannel( console.log('adding channel')
dmUserId, ChatProvider.addUserToChannel(
channelId, dmUserId,
[ws.name, 1, Date.now(), user.id], channelId,
); [ws.name, 1, Date.now(), user.id],
} );
} }
} }

View File

@ -18,19 +18,10 @@ export default (store) => (next) => (action) => {
break; break;
} }
/* case 'SET_NAME':
* TODO case 'LOGIN:':
* make LOGIN / LOGOUT Actions instead of comparing name changes case 'LOGOUT': {
*/ ProtocolClient.reconnect();
case 'RECEIVE_ME': {
const { name } = action;
ProtocolClient.setName(name);
break;
}
case 'SET_NAME': {
const { name } = action;
ProtocolClient.setName(name);
break; break;
} }