87 lines
2.3 KiB
C
87 lines
2.3 KiB
C
/* SPDX-License-Identifier: MIT */
|
|
/* Copyright (c) 2026 Oleksandr Zhylin */
|
|
|
|
#include <db.h>
|
|
#include "main.h"
|
|
#include "session.h"
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
int32_t create_user(session *sess, char *line) {
|
|
i_db_user_create p;
|
|
int32_t privileges;
|
|
int32_t res;
|
|
if (sscanf(line, "register %s %s %s", p.uname, p.pass, p.email) == 3) {
|
|
res = db_user_create(&p);
|
|
if (res > 0) {
|
|
sess->state = OP_WAIT;
|
|
sess->uname = malloc(strlen(p.uname)+1);
|
|
strcpy(sess->uname, p.uname);
|
|
sess->uid = res;
|
|
sess->privileges = 1; /* by default */
|
|
session_send_string(sess, "ok\n");
|
|
} else if (res == -2) {
|
|
session_send_string(sess, "User with such name already exists\n");
|
|
} else if (res == -3) {
|
|
session_send_string(sess, "User with such email already exists\n");
|
|
} else {
|
|
session_send_string(sess, "Error creating the user\n");
|
|
}
|
|
return res;
|
|
};
|
|
return 0;
|
|
}
|
|
|
|
uint32_t process_user_name(char *line, session *sess) {
|
|
if (!strncmp(line, "exit", sizeof "exit")) {
|
|
sess->state = ERR;
|
|
sess->reason = EXIT;
|
|
session_send_string(sess, "Bye!");
|
|
return 1;
|
|
}
|
|
|
|
if (!strncmp(line, "register", sizeof "register" - 1)) {
|
|
return create_user(sess, line);
|
|
}
|
|
|
|
if (!strncmp(line, "anonymous", sizeof "anonymous")) {
|
|
sess->uname = malloc(sizeof "anonymous");
|
|
strcpy(sess->uname, "anonymous");
|
|
sess->state = OP_WAIT;
|
|
session_send_string(sess, "Welcome, Anonymous!");
|
|
return 3;
|
|
}
|
|
|
|
sess->uname = malloc(strlen(line) + 1);
|
|
strcpy(sess->uname, line);
|
|
sess->state = OP_LOGIN_PSS;
|
|
session_send_string(sess, "password> ");
|
|
|
|
return 0;
|
|
}
|
|
|
|
/* returns 1 if success */
|
|
int login(session *sess, char *pass) {
|
|
char tmp_string[256];
|
|
i_auth_t cred;
|
|
o_auth_t response;
|
|
cred.name = sess->uname;
|
|
cred.pass = pass;
|
|
response.uid = 0;
|
|
db_user_auth(&cred, &response);
|
|
if (response.uid) {
|
|
sess->state = OP_WAIT;
|
|
sess->privileges = (char)atoi(&response.privileges);
|
|
sess->uid = response.uid;
|
|
sprintf(tmp_string, "Welcome, %s\n", sess->uname);
|
|
session_send_string(sess, tmp_string);
|
|
return 0;
|
|
} else {
|
|
sprintf(tmp_string, "login_again>\n");
|
|
session_send_string(sess, tmp_string);
|
|
sess->state = OP_LOGIN_USR;
|
|
return 1;
|
|
}
|
|
} |