private static async Task <(bool success, string result)> LoginWithForm(HttpContext context) { using var connection = Database.OpenNewConnection(); var form = context.Request.Form; string email = form["email"].ToString().NormalizeEmail(); string password = form["password"]; bool success = await AuthenticateUser(email, password, connection); if (success) { var userid = await UserIdFromEmail(email, connection); var token = await UserSessions.CreateNewSession(userid, connection); return(true, token); } else { return(false, "This combination of email and password was not found"); } }
private static async Task <(bool success, string result)> RegisterWithForm(HttpContext context) { if (context.Request.HasFormContentType) { var form = context.Request.Form; string username = form["username"].ToString().Trim(); string password = form["password"].ToString(); string passwordConfirmation = form["password-confirmation"].ToString(); string email = form["email"].ToString().NormalizeEmail(); if (username.Length < 3) { return(false, "Username too short"); } var(success, result) = ValidatePassword(password, passwordConfirmation); if (!success) { return(false, result); } //NOTE(Simon): Shortest possible is [email protected] if (email.Length < 5) { return(false, "Email too short"); } using var connection = Database.OpenNewConnection(); bool userExists = await UserExists(email, connection); string hashedPassword = BCrypt.Net.BCrypt.HashPassword(password, bcryptWorkFactor); if (!userExists) { string verificationToken = Tokens.NewVerifyEmailToken(); int querySuccess = await connection.ExecuteAsync(@"insert into users (username, email, pass, verification_token) values (@username, @email, @hashedPassword, @verificationToken)" , new { username, email, hashedPassword, verificationToken }); if (querySuccess == 0) { throw new Exception("Something went wrong while writing new user to db"); } await EmailClient.SendEmailConfirmationMail(email, verificationToken); } else { return(false, "This user already exists"); } //NOTE(Simon): Create session token to immediately log user in. { int userid = await UserIdFromEmail(email, connection); string token = await UserSessions.CreateNewSession(userid, connection); return(true, token); } } else { return(false, "Request did not contain a form"); } }