Skip to content

Commit

Permalink
session login fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
evolutionleo committed Nov 28, 2024
1 parent de985f3 commit d36e5d3
Show file tree
Hide file tree
Showing 13 changed files with 128 additions and 28 deletions.
6 changes: 6 additions & 0 deletions Client/objects/oLoginMenu/Create_0.gml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ global.canvas = new SUICanvas()

global.canvas.appendChild(new SUIBackButton())

txt_account = global.canvas.appendChild(new SUIText(20, room_height-80,
SUIBind(function() { return $"account: {global.account}\nprofile: {global.profile}" })))

txt_title = global.canvas.appendChild(new SUITitle(0, room_height/2 - 120, "Login"))
txt_title.set("center", room_width/2)

Expand All @@ -32,5 +35,8 @@ var btn_w = 120
var btn_h = 40
btn_register = global.canvas.appendChild(new SUIButton(tb_login.get("left"), _y, "register", function() { sendRegister(username, password) }, {w: btn_w, h: btn_h}))
btn_login = global.canvas.appendChild(new SUIButton(0, _y, "log in", function() { sendLogin(username, password) }, {w: btn_w, h: btn_h}))
btn_delete = global.canvas.appendChild(new SUIButton(0, 60, "delete session", function() { file_delete(SESSION_FILE); }, {w: 160, h: btn_h}))

btn_delete.set("right", room_width-20)

btn_login.set("right", tb_password.get("right"))
5 changes: 5 additions & 0 deletions Client/options/windows/options_windows.yy

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Client/scripts/WarpEvents/WarpEvents.gml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ function onConnect() {
sendHello()
sendClientInfo()
sendRequestTime()
sendNameGet()
//sendNameGet()

sendSession()
}

function onDisconnect() {
Expand Down
2 changes: 2 additions & 0 deletions Client/scripts/__WarpConfig/__WarpConfig.gml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ if (!CONFIGS_SET) {
}


#macro SESSION_FILE $"session{MultiClientGetID()}.token"
#macro OLD_SESSIONS_FILE "sessions_old.token"
#macro CONNECT_TIMEOUT 60 * 5 // 5 seconds


Expand Down
49 changes: 39 additions & 10 deletions Client/scripts/authHandlers/authHandlers.gml
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,48 @@ addHandler("register", function(data) {
})


addHandler("session create", function(data) {

var sessionHandler = function(data) {
if (data.success) {
var file = file_text_open_write("session.token")
file_text_write_string(file, data.session)
var session = data.session

// we save the history of all old sessions just in case
if (file_exists(SESSION_FILE) and OLD_SESSIONS_FILE != "") {
var f1 = file_text_open_read(SESSION_FILE)
var f2 = file_text_open_append(OLD_SESSIONS_FILE)
file_text_write_string(f2, file_text_read_string(f1))
file_text_writeln(f2)
file_text_close(f1)
file_text_close(f2)
}

// write the new received session
var file = file_text_open_write(SESSION_FILE)
file_text_write_string(file, session)
file_text_close(file)

global.session = session

if (data.cmd == "session create") {
trace("Session created successfully.")
}
else if (data.cmd == "session login") {
trace("Session login successful.")
}
}
else {
trace("Failed to create a session. Reason: %", data.reason)
if (data.cmd == "session create") {
trace("Failed to create a session. Reason: %", data.reason)
}
else if (data.cmd == "session login") {
trace("Failed to login with a session. Reason: %", data.reason)

// create a new session if the old one didn't work
//sendSessionCreate()
}
}
})
}

addHandler("session login", function(data) {
var success = data.success


})

addHandler("session create", sessionHandler)
addHandler("session login", sessionHandler)
25 changes: 25 additions & 0 deletions Client/scripts/authSenders/authSenders.gml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,29 @@ function sendRegister(username, password) {

function sendNameGet() {
send({cmd: "name get"})
}

function sendSessionCreate() {
send({cmd: "session create"})
}

function sendSessionLogin(session) {
send({cmd: "session login", session})
}

function sendSession() {
if (file_exists(SESSION_FILE)) {
var file = file_text_open_read(SESSION_FILE)
var session = file_text_read_string(file)
file_text_close(file)

trace(SESSION_FILE)
trace("read session: %", session)

global.session = session
sendSessionLogin(session)
}
else {
sendSessionCreate()
}
}
14 changes: 10 additions & 4 deletions TypescriptServer/src/cmd/handlers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { addHandler } from "#cmd/handlePacket";
import { Account, getAccountInfo, IAccount } from "#schemas/account";
import Session from "#schemas/session";
import { accountCreate, accountLogin, accountRegister, sessionCreate, sessionGet, sessionLogin } from "#util/auth";
import trace from "#util/logging";
import { Names } from "#util/names";

addHandler('name get', (c) => {
c.sendName();
});

// create a brand new (temporary) account

addHandler('session create', async (c, data) => {
let name = c.name; // default name

Expand All @@ -18,25 +20,29 @@ addHandler('session create', async (c, data) => {

await c.register(c.account);

c.send({ cmd: 'session create', success: true, account: getAccountInfo(c.account), session: c.session.token });
c.send({ cmd: 'session create', success: true, session: c.session.token });
c.sendLogin(true);
}
catch (reason) {
c.send({ cmd: 'session create', success: false, reason: reason });
c.send({ cmd: 'session create', success: false, reason: reason.toString() });
}
});

addHandler('session login', async (c, data) => {
let token = data.session;
trace('session token login: ' + token);

try {
c.session = await sessionGet(token);
c.account = await sessionLogin(c.session);

await c.login(c.account);
c.send({ cmd: 'session login', success: true });
c.send({ cmd: 'session login', success: true, session: c.session.token });
c.sendLogin(true);
}
catch(reason) {
c.send({ cmd: 'session login', success: false, reason: reason });
trace('error: ' + reason.toString());
c.send({ cmd: 'session login', success: false, reason: reason.toString() });
}
});

Expand Down
31 changes: 26 additions & 5 deletions TypescriptServer/src/concepts/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ export default class Client extends SendStuff implements IClient {
ping: number;

room_join_timer: number = -1; // if >0 - joined a room recently
reconnect_timer: number = -1;

/** @type {boolean} */
get logged_in() {
Expand Down Expand Up @@ -237,17 +238,19 @@ export default class Client extends SendStuff implements IClient {
else {
(this.socket as TCPSocket).destroy();
}
}

onDisconnect() {
this.socket = null;
this.connected = false;
}

onDisconnect() {
this.reconnect_timer = config.reconnect_timeout;

// go offline
if (this.logged_in) {
this.profile.online = false;
this.profile.last_online = new Date();
this.save();
}
}

Expand All @@ -265,6 +268,8 @@ export default class Client extends SendStuff implements IClient {


global.clients.splice(global.clients.indexOf(this), 1);

this.disconnect();
}

// insert this socket into a "dead" (disconnected) client
Expand All @@ -282,6 +287,13 @@ export default class Client extends SendStuff implements IClient {
return old_client;
}

onReconnect() {
if (this.lobby)
this.sendLobbyJoin(this.lobby);
if (this.room && this.entity)
this.sendPlay(this.lobby, this.room, this.entity.pos, this.entity.uuid);
}


getInfo():ClientInfo {
return {
Expand Down Expand Up @@ -546,7 +558,7 @@ export default class Client extends SendStuff implements IClient {
if (this.account !== null) {
this.account.save()
.then(() => {
trace('Saved the account successfully');
// trace('Saved the account successfully');
})
.catch((err) => {
trace('Error while saving account: ' + err);
Expand All @@ -560,12 +572,21 @@ export default class Client extends SendStuff implements IClient {

this.profile.save()
.then(() => {
trace('Saved the profile successfully.');
// trace('Saved the profile successfully.');
})
.catch((err) => {
trace('Error while saving profile: ' + err);
});
}
if (this.session !== null) {
this.session.save()
.then(() => {
// trace('Saved the session successfully');
})
.catch((err) => {
trace('Error while saving session: ' + err);
})
}
}

/**
Expand Down
3 changes: 2 additions & 1 deletion TypescriptServer/src/concepts/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,8 @@ class Room extends EventEmitter {
}
// find a new start position
else {
const p = this.level.getStartPos(this.players.length-1);
// const p = this.level.getStartPos(this.players.length-1);
const p = this.level.getStartPos(this.players.indexOf(player));
x = p.x;
y = p.y;
}
Expand Down
2 changes: 2 additions & 0 deletions TypescriptServer/src/schemas/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ export default Account;


export type AccountInfo = {
id: string,
username: string
}

export function getAccountInfo(a:IAccount):AccountInfo {
if (a === null) return null;

return {
id: a.id,
username: a.username
};
}
4 changes: 2 additions & 2 deletions TypescriptServer/src/schemas/session.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Schema, Model, ObjectId, model } from 'mongoose'
import { Schema, Model, ObjectId, model, Document } from 'mongoose'

export interface ISession {
export interface ISession extends Document {
token: string,
account_id: ObjectId,
updatedAt: Date,
Expand Down
6 changes: 3 additions & 3 deletions TypescriptServer/src/util/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ export function profileCreate(account:IAccount):IProfile { // for when just regi
});
}

export function accountCreate(username: string, password = '', temporary = true):IAccount {
export function accountCreate(username: string, password = '_', temporary = true):IAccount {
if (!temporary) {
password = hashPassword(password);
}
else {
password = '';
password = '_';
}

return new Account({
Expand Down Expand Up @@ -136,7 +136,7 @@ export async function sessionGet(session_token: string):Promise<ISession> {
}

export async function sessionLogin(session: ISession):Promise<IAccount> {
const account = await Account.findOne({ id: session.account_id });
const account = await Account.findOne({ _id: session.account_id });
if (!account) {
throw 'account does not exist';
}
Expand Down
5 changes: 3 additions & 2 deletions TypescriptServer/src/util/names.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ export class Names {
static guest_counter = 1;

static getDefaultName():string {
let s = (this.guest_counter++).toString();
s = '0'.repeat(3 - s.length) + s;
// let s = (this.guest_counter++).toString();
let s = Math.floor(Math.random() * 1000000).toString();
s = '0'.repeat(6 - s.length) + s;
return 'Guest' + s;
}

Expand Down

0 comments on commit d36e5d3

Please sign in to comment.