update account creation + db creation, add updateMail

master
remrem 2 years ago
parent e5e1de913f
commit 133757e9c4

1
.gitignore vendored

@ -3,5 +3,6 @@
.packages .packages
# server.dart compiled executable # server.dart compiled executable
server server
server.exe
# Conventional directory for build output. # Conventional directory for build output.
build/ build/

@ -16,7 +16,7 @@ final _router = Router()
..post('/user/account', API.createAccount) // vrai post ..post('/user/account', API.createAccount) // vrai post
// PUT // PUT
..put('/user/master-password', API.changeMasterPassword) ..put('/user/master-password', API.changeMasterPassword)
..put('/user/password-file', API.uploadPasswordDb) ..post('/user/password-file', API.uploadPasswordDb)
..put('/user/change-mail', API.changeMail) ..put('/user/change-mail', API.changeMail)
// DELETE // DELETE
..delete('/user/account', API.deleteAccount); ..delete('/user/account', API.deleteAccount);
@ -49,7 +49,7 @@ void main(List<String> args) async {
final handler = Pipeline().addMiddleware(logRequests()).addHandler(_router); final handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);
// For running in containers, we respect the PORT environment variable. // For running in containers, we respect the PORT environment variable.
final port = int.parse(Platform.environment['PORT'] ?? '8080'); final port = int.parse(Platform.environment['PORT'] ?? '8989');
final server = await serve(handler, ip, port); final server = await serve(handler, ip, port);
print('Server listening on port ${server.port}'); print('Server listening on port ${server.port}');
} }

@ -1,3 +1,4 @@
import 'dart:io';
import 'package:passworld_api/db_to_api.dart'; import 'package:passworld_api/db_to_api.dart';
import 'package:postgres/postgres.dart'; import 'package:postgres/postgres.dart';
import 'package:shelf/shelf.dart'; import 'package:shelf/shelf.dart';
@ -23,7 +24,7 @@ class API {
if (await checkRequiredFields(required, body)) { if (await checkRequiredFields(required, body)) {
try { try {
await AccountsToPostgres.selectHashById(body[required[0]]); await AccountsToPostgres.selectHashByMail(body[required[0]]);
} catch (e) { } catch (e) {
return Response(404, return Response(404,
body: 'Not Found'); // no hash found -> 404 (Not Found) body: 'Not Found'); // no hash found -> 404 (Not Found)
@ -67,8 +68,8 @@ class API {
if (await checkRequiredFields(required, body)) { if (await checkRequiredFields(required, body)) {
// List<String> twofa = body[required[3]]; // List<String> twofa = body[required[3]];
try { try {
await AccountsToPostgres.create(body[required[0]], body[required[1]], await AccountsToPostgres.createAccount(body[required[0]],
body[required[2]] /*, twofa*/); body[required[1]], body[required[2]] /*, twofa*/);
} catch (e) { } catch (e) {
return Response(409, return Response(409,
body: 'Account already existing'); // 409 (Conflict) body: 'Account already existing'); // 409 (Conflict)
@ -86,17 +87,49 @@ class API {
// Update master password // Update master password
static Response changeMasterPassword(Request req) { static Response changeMasterPassword(Request req) {
return Response.ok("master password chnaged"); return Response.ok("master password changed");
} }
// Update mail // Update mail
static Response changeMail(Request req) { static Future<Response> changeMail(Request req) async {
return Response.ok("master password chnaged"); final List<String> required = ["email", "newMail"];
final body = await bodyToJson(req);
if (await checkRequiredFields(required, body)) {
try {
await AccountsToPostgres.updateMail(
body[required[0]], body[required[1]]);
} catch (e) {
return Response(403,
body: 'This is not the good password'); // 403 (Forbidden)
}
return Response(201,
body: 'user\'s mail succesfully changed'); // 201 (Created)
} else {
return Response.badRequest(body: 'Bad request'); // 400 (Bad Request)
}
} }
// Upload sqlite password file // Upload sqlite password file
static Response uploadPasswordDb(Request req) { static Future<Response> uploadPasswordDb(Request req) async {
return Response.ok(""); sleep(Duration(seconds: 20));
Stream<List<int>> fileStream =
await req.read(); // await is needed even if IDE say no
List<List<int>> tmpFile = await fileStream.toList();
List<int> fileAsBytes = tmpFile[0];
File file = File("./passfile");
file.writeAsBytes(fileAsBytes);
print(await file.stat());
//File test = File("./haha.yu");
//await test.writeAsBytes(listBytes);
//print(await test.stat());
//print("Bytes: $listBytes");
//print("Lenght: $size");
return Response.ok("API: file received");
} }
/*---------------| /*---------------|

@ -1,5 +1,4 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:ffi';
import 'dart:io'; import 'dart:io';
import 'package:postgres/postgres.dart'; import 'package:postgres/postgres.dart';
@ -9,16 +8,16 @@ class AccountsToPostgres {
// username: 'pass', password: '1p2a3s4s5'); // username: 'pass', password: '1p2a3s4s5');
/* Dev RemRem */ /* Dev RemRem */
// static final connection = PostgreSQLConnection("localhost", 5432, 'passworld', static final connection = PostgreSQLConnection("localhost", 5432, 'passworld',
// username: 'hel', password: ''); username: 'hel', password: '');
/* Production */ /* Production */
static final connection = PostgreSQLConnection( // static final connection = PostgreSQLConnection(
Platform.environment["DB_SERVER"]!, // Platform.environment["DB_SERVER"]!,
5432, // 5432,
Platform.environment["DB_DATABASE"]!, // Platform.environment["DB_DATABASE"]!,
username: Platform.environment["DB_USER"], // username: Platform.environment["DB_USER"],
password: Platform.environment["DB_PASSWORD"]); // password: Platform.environment["DB_PASSWORD"]);
AccountsToPostgres() { AccountsToPostgres() {
//initConnection(); //initConnection();
@ -38,20 +37,32 @@ class AccountsToPostgres {
static Future<void> createAccountTable() async { static Future<void> createAccountTable() async {
await openConnection(); await openConnection();
await connection await connection.query("""
.query( CREATE TABLE IF NOT EXISTS \"Account\"(
"CREATE TABLE IF NOT EXISTS \"Account\"(id TEXT PRIMARY KEY,hash TEXT NOT NULL,salt TEXT NOT NULL,twofa VARCHAR(50)[],passwords INTEGER[])") id INT PRIMARY KEY,
.then((value) { mail TEXT NOT NULL UNIQUE,
print("🟦 Account Table Created"); hash TEXT NOT NULL,
}); salt TEXT NOT NULL,
twofa VARCHAR(50)[],
password_file INTEGER[]
)""");
await connection.query("""
CREATE SEQUENCE IF NOT EXISTS plus1id
INCREMENT 1
START 1""");
print("🟦 Account Table Created");
} }
// Add support for twoFa if needed // Add support for twoFa if needed
static Future<void> create(String email, String hash, static Future<void> createAccount(
String salt /*, List<String> twoFaStr*/) async { String mail, String hash, String salt /*, List<String> twoFaStr*/) async {
await connection.query("INSERT INTO \"Account\" VALUES(@id,@hash,@salt)", await checkMailAlreadyExist(mail); // TODO: throw execption if != null
await connection.query(
"INSERT INTO \"Account\" VALUES(nextval('plus1id'),@mail,@hash,@salt)",
substitutionValues: { substitutionValues: {
"id": email, "mail": mail,
"hash": hash, "hash": hash,
"salt": salt /*, "salt": salt /*,
"twofa": twoFaStr*/ "twofa": twoFaStr*/
@ -59,54 +70,67 @@ class AccountsToPostgres {
print("✅ Account succesfully created"); print("✅ Account succesfully created");
} }
static Future<String> selectHashById(String id) async { static Future<String> selectHashByMail(String mail) async {
List<List<dynamic>> results = await connection.query( List<List<dynamic>> results = await connection.query(
"SELECT hash FROM \"Account\" WHERE id=@identifiant", "SELECT hash FROM \"Account\" WHERE mail=@mail",
substitutionValues: {"identifiant": id}); substitutionValues: {"mail": mail});
closeConnection();
return results[0][0]; return results[0][0];
} }
static Future<void> updatePass( static Future<void> checkMailAlreadyExist(String mail) async {
String identifiant, String hash, String salt) async { List<List<dynamic>> results = await connection.query(
if (selectHashById(identifiant) == null) { "SELECT id FROM \"Account\" WHERE mail=@mail",
substitutionValues: {"mail": mail});
print(results[0][0]);
return;
}
static Future<void> updatePass(String mail, String hash, String salt) async {
if (selectHashByMail(mail) == null) {
return; return;
} else { } else {
await connection.query( await connection.query(
"UPDATE \"Account\" SET hash=@h, salt=@s WHERE id=@identifiant", "UPDATE \"Account\" SET hash=@hash, salt=@salt WHERE mail=@mail",
substitutionValues: { substitutionValues: {"mail": mail, "hash": hash, "salt": salt});
"identifiant": identifiant,
"h": hash,
"s": salt
});
} }
} }
static Future<void> updateFilePass( static Future<void> updateFilePass(String mail, File passwordFile) async {
String identifiant, File passwordFile) async {
List<int> passwordBlob = List<int> passwordBlob =
utf8.encode(await passwordFile.readAsString(encoding: utf8)); utf8.encode(await passwordFile.readAsString(encoding: utf8));
if (selectHashById(identifiant) == null) { if (selectHashByMail(mail) == null) {
return; return;
} else { } else {
await connection.query( await connection.query(
"UPDATE \"Account\" SET passwords=@p WHERE id=@identifiant", "UPDATE \"Account\" SET passwords=@p WHERE id=@identifiant",
substitutionValues: {"identifiant": identifiant, "p": passwordBlob}); substitutionValues: {"identifiant": mail, "p": passwordBlob});
} }
} }
static Future<void> updateTwoFa(String identifiant, List<String> tfa) async { static Future<void> updateTwoFa(String mail, List<String> tfa) async {
List<String> twoFaStr = List.empty(growable: true); List<String> twoFaStr = List.empty(growable: true);
if (selectHashById(identifiant) == null) { if (selectHashByMail(mail) == null) {
return; return;
} else { } else {
await connection.query( await connection.query(
"UPDATE \"Account\" SET twofa=@tfa WHERE id=@identifiant", "UPDATE \"Account\" SET twofa=@tfa WHERE id=@identifiant",
substitutionValues: {"identifiant": identifiant, "tfa": tfa}); substitutionValues: {"identifiant": mail, "tfa": tfa});
}
}
static Future<void> updateMail(String mail, String newMail) async {
if (selectHashByMail(mail) == null) {
return;
} else {
await connection.query(
"UPDATE \"Account\" SET mail=@newMail WHERE mail=@mail",
substitutionValues: {"newMail": newMail, "mail": mail});
} }
print("✅ Mail succesfully updated");
} }
static Future<void> deleteById(String id) async { static Future<void> deleteById(String id) async {

@ -163,12 +163,12 @@ packages:
source: hosted source: hosted
version: "1.8.0" version: "1.8.0"
mime: mime:
dependency: transitive dependency: "direct main"
description: description:
name: mime name: mime
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.0.2" version: "1.0.3"
node_preamble: node_preamble:
dependency: transitive dependency: transitive
description: description:

@ -8,6 +8,7 @@ environment:
dependencies: dependencies:
args: ^2.0.0 args: ^2.0.0
mime: ^1.0.3
path: ^1.8.2 path: ^1.8.2
postgres: ^2.5.2 postgres: ^2.5.2
shelf: ^1.1.0 shelf: ^1.1.0

Loading…
Cancel
Save