public async Task <AuthenticatedUser> SignIn(User user)
        {
            var dbUser = await _context.Users
                         .FirstOrDefaultAsync(u => u.Email == user.Email);

            if (dbUser == null || _passwordHasher.VerifyHashedPassword(dbUser.Password, user.Password) == PasswordVerificationResult.Failed)
            {
                throw new InvalidEmailPasswordException("Invalid Username or Password");
            }

            return(new AuthenticatedUser
            {
                Token = JwtGenerator.GenerateUserToken(user.Email),
                Email = user.Email,
                Password = user.Password,
                Name = dbUser.Name
            });
        }
Exemple #2
0
        /// <summary>
        /// logging into a user's account
        /// </summary>
        /// <param name="user"></param>
        /// <returns> user's username, JWT token, their ID </returns>
        public async Task <AuthenticatedUser> SignIn(Strength.DB.User user)
        {
            // finding user in the database
            var dbUser = await _context.Users
                         .FirstOrDefaultAsync(u => u.Email == user.Email);

            // checking if user was found and if given password matches password in the database
            if (dbUser == null || _passwordHasher.VerifyHashedPassword(dbUser.Password, user.Password) == PasswordVerificationResult.Failed)
            {
                throw new InvalidUsernamePasswordException("Invalid username or password");
            }

            return(new AuthenticatedUser
            {
                Username = dbUser.Username,
                Token = JwtGenerator.GenerateUserToken(dbUser.Username),
                Id = dbUser.Id
            });
        }
Exemple #3
0
        public string ChangeUsername(string username)
        {
            // finding user in the database
            var dbUser = _context.Users
                .FirstOrDefault(u => u.Id == _user.Id);

            // checking if user was found and verifying his password
            if (dbUser == null)
            {
                throw new DoesNotMatchIdException("User not found");
            }

            if (_context.Users.Any(u => u.Username == username)){
                throw new UsernameAlreadyExistsException("This username is taken. Try another one.");
            }

            dbUser.Username = username;

            _context.SaveChanges();
            return JwtGenerator.GenerateUserToken(username);
        }
        public async Task <AuthenticatedUser> SignUp(User user)
        {
            var checkUser = await _context.Users
                            .FirstOrDefaultAsync(u => u.Email.Equals(user.Email));

            if (checkUser != null)
            {
                throw new EmailAlreadyExistsException("Email Already Exists");
            }

            user.Password = _passwordHasher.HashPassword(user.Password);
            await _context.AddAsync(user);

            await _context.SaveChangesAsync();

            return(new AuthenticatedUser
            {
                Token = JwtGenerator.GenerateUserToken(user.Email),
                Email = user.Email,
                Password = user.Password,
                Name = user.Name
            });
        }
Exemple #5
0
        /// <summary>
        /// creating a new account
        /// </summary>
        /// <param name="user"></param>
        /// <returns> their username, JWT token and ID </returns>
        public async Task <AuthenticatedUser> SignUp(Strength.DB.User user)
        {
            // checking if username exists
            var checkUser = await _context.Users
                            .FirstOrDefaultAsync(u => u.Username.Equals(user.Username) || u.Email.Equals(user.Email));

            if (checkUser != null)
            {
                if (checkUser.Username == user.Username)
                {
                    throw new UsernameAlreadyExistsException("Username already exists");
                }
                else
                {
                    throw new EmailAlreadyExistsException("Email already exists");
                }
            }

            // checking if email is legitimate
            bool isEmail = Regex.IsMatch(user.Email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);

            if (!isEmail)
            {
                throw new Exception("Invalid email");
            }

            // checking if password is strong enough
            var   regexPasswordCheck = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})";
            Match match = Regex.Match(user.Password, regexPasswordCheck);

            if (!match.Success)
            {
                throw new Exception("Password is too weak");
            }

            // hashing password
            user.Password = _passwordHasher.HashPassword(user.Password);

            // generating random ID
            Random ran           = new Random();
            string id            = ran.Next(100, 2048).ToString();
            Int64  unixTimestamp = (Int64)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

            id += unixTimestamp.ToString();

            for (int i = 0; i < 2; i++)
            {
                id += ran.Next(1000, 3048).ToString();
            }
            byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(id);

            // assigning generated ID
            user.Id = Convert.ToBase64String(toEncodeAsBytes);

            // save changes
            await _context.AddAsync(user);

            await _context.SaveChangesAsync();

            return(new AuthenticatedUser
            {
                Username = user.Username,
                Token = JwtGenerator.GenerateUserToken(user.Username),
                Id = user.Id
            });
        }