Exemple #1
0
        public async Task <GenericResponse <string> > Register(RegisterRequest registerRequest)
        {
            // Create user
            byte[] salt    = AuthTools.GetRandomSalt();
            string hash    = AuthTools.GetHash(registerRequest.Password, salt);
            TUser  newUser = new TUser()
            {
                RegisterDate = DateTime.UtcNow,
                Email        = registerRequest.Email,
                Username     = registerRequest.Username,
                PasswordHash = hash,
                PasswordSalt = Convert.ToBase64String(salt)
            };

            try
            {
                await _databaseContext.TUser.AddAsync(newUser);

                await _databaseContext.SaveChangesAsync();
            }
            catch (DbUpdateException e)
            {
                return(new GenericResponse <string>("Cannot register with these informations", e));
            }

            return(new GenericResponse <string>(AuthTools.GetJwtToken(_configuration, newUser)));
        }
Exemple #2
0
        public async Task <GenericResponse <string> > Login(LoginRequest loginRequest)
        {
            // Check if user exist
            TUser dbUser;

            try
            {
                dbUser = _databaseContext.TUser.FirstOrDefault(u => u.Username == loginRequest.Username);
            }
            catch (Exception e)
            {
                return(GetLoginErrorResponse(e));
            }
            if (dbUser == null)
            {
                return(GetLoginErrorResponse());
            }

            // Check hash
            string hashed = AuthTools.GetHash(loginRequest.Password, Convert.FromBase64String(dbUser.PasswordSalt));

            if (hashed == dbUser.PasswordHash)
            {
                return(new GenericResponse <string>(AuthTools.GetJwtToken(_configuration, dbUser)));
            }
            return(GetLoginErrorResponse());
        }