コード例 #1
0
        public async Task <IActionResult> Register([FromBody] RegisterDto model)
        {
            if (ModelState.IsValid)
            {
                var newUser = new User()
                {
                    Email        = model.Email,
                    FirstName    = model.FirstName,
                    IsActivated  = false,
                    LastName     = model.LastName,
                    Password     = PasswordUtils.HashPassword(model.Password),
                    Role         = "User",
                    UserName     = model.UserName,
                    CreatedOnUtc = DateTime.Now,
                    Valid        = true
                };

                MessageDto result = await _userService.Insert(newUser);

                if (result.Success)
                {
                    return(new OkObjectResult(result));
                }
                return(BadRequest(result));
            }

            var errors = ModelState.Select(x => x.Value.Errors)
                         .Where(y => y.Count > 0)
                         .ToList()
                         .Select(c => c.Select(x => x.ErrorMessage).FirstOrDefault());

            return(BadRequest(errors));
        }
コード例 #2
0
ファイル: RegisterService.cs プロジェクト: tiasmt/napper_be
 public bool Register(User user)
 {
     if (Validate())
     {
         //Create the salt value with a cryptographic PRNG:
         new RNGCryptoServiceProvider().GetBytes(user.Salt = new byte[16]);
         user.HashedPassword = PasswordUtils.HashPassword(user.Salt, user.Password);
         _storage.Create(user);
         return(true);
     }
     return(false);
 }
コード例 #3
0
ファイル: LoginService.cs プロジェクト: tiasmt/napper_be
        public AuthenticateResponse Login(string username, string password)
        {
            var user           = _storage.GetByUsername(username);
            var hashedPassword = PasswordUtils.HashPassword(user.Salt, password);

            if (hashedPassword == user.HashedPassword)
            {
                var token = generateJwtToken(user);
                return(new AuthenticateResponse(user, token));
            }
            else
            {
                throw new NotFoundException($"Invalid username / password.");
            }
        }
コード例 #4
0
        internal static void AddDefaultClientLogin(this Tuple <Client, GatewayDbContext> clientResult)
        {
            var client            = clientResult.Item1;
            var dbContext         = clientResult.Item2;
            var defaultUserIdGuid = new Guid(DefaultUserId);

            var defaultLogin = client.UserAccounts.FirstOrDefault(login => login.UserId == defaultUserIdGuid);

            if (defaultLogin == null)
            {
                defaultLogin            = UserAccount.CreateNewUser();
                defaultLogin.ClientId   = client.Id;
                defaultLogin.UserId     = defaultUserIdGuid;
                defaultLogin.UserSecret = PasswordUtils.HashPassword(DefaultSecret, defaultLogin.Salt);

                dbContext.Add(defaultLogin);
            }
        }
コード例 #5
0
ファイル: LoginController.cs プロジェクト: edenerez/CompAgri
        public UserDto Post([FromBody] UserDto user)
        {
            User userFromDatabase = null;

            using (var db = new CompAgriConnection())
            {
                if (user.Email == null && user.UserName == null)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }

                if (user.Email != null)
                {
                    userFromDatabase = db.User.FirstOrDefault(u => u.Email == user.Email);
                }

                if (userFromDatabase == null && user.UserName != null)
                {
                    userFromDatabase = db.User.FirstOrDefault(u => u.UserName == user.UserName);
                }

                if (userFromDatabase == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }

                var hashedPassword = PasswordUtils.HashPassword(user.Password, userFromDatabase.PasswordSalt);

                if (hashedPassword != userFromDatabase.Password)
                {
                    throw new HttpResponseException(HttpStatusCode.Forbidden);
                }
                else
                {
                    userFromDatabase.Token = TokenUtils.GenerateToken();
                    db.SaveChanges();
                    LogUserLogged(userFromDatabase);

                    var userToSend = new UserDto(userFromDatabase, true);
                    return(userToSend);
                }
            }
        }
コード例 #6
0
 async private void btnRegister_Clicked(object sender, EventArgs e)
 {
     try //stop application crashing if invalid
     {
         //TODO Input verification
         if (db.EmailRegistered(tbEmail.Text))
         {
             ErrorMessage.Text = "Email already registered!";
             return;
         }
         if (tbPassword.Text != tbConfirmPassword.Text)
         {
             ErrorMessage.Text = "Passwords do not match";
             return;
         }
         if (!Regex.IsMatch(tbEmail.Text, "^[a - zA - Z0 - 9.!#$%&amp;'*+/=?^_`{|}~-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"))
         {
             ErrorMessage.Text = "Invalid Email";
             return;
         }
         User user = new User()
         {
             FirstName   = tbFirstname.Text,
             Surname     = tbSurname.Text,
             Email       = tbEmail.Text,
             Password    = PasswordUtils.HashPassword(tbPassword.Text),
             AccountType = pckrAccount.SelectedItem.ToString()
         };
         int userId = db.InsertUser(user);
         user.ID           = userId;
         mainPage.MainPage = new NavigationPage(new HomeP(user));
     }
     catch
     {
         Debug.WriteLine("Error");
     }
 }
コード例 #7
0
ファイル: UserController.cs プロジェクト: edenerez/CompAgri
        public UserDto Post([FromBody] UserDto userDto)
        {
            if (!userDto.IsValid())
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            using (var db = new CompAgriConnection())
            {
                var previousUser = db.User.FirstOrDefault(u => (u.UserName != null && u.UserName == userDto.UserName) || (u.Email != null && u.Email == userDto.Email));
                if (previousUser != null)
                {
                    throw WebExceptionsFactory.GetUserDuplicatedException();
                }

                var userBeforeSave = userDto.User();
                userBeforeSave.PasswordSalt = PasswordUtils.GenerateSalt();
                userBeforeSave.Password     = PasswordUtils.HashPassword(userBeforeSave.Password, userBeforeSave.PasswordSalt);

                var user = db.User.Add(userBeforeSave);
                db.SaveChanges();
                return(new UserDto(user));
            }
        }
コード例 #8
0
 public void Setup()
 {
     _hashedPassword = PasswordUtils.HashPassword(_plainPassword, _salt);
 }
コード例 #9
0
        public static Task <uint> TryAuthenicateAsync(string identifier, string password)
        {
            Task <DbDataReader> userDataTask = null;
            DatabaseConnection  dbConnection = new DatabaseConnection();

            try
            {
                try
                {
                    new MailAddress(identifier); //TODO: Alternativly we could use regex

                    userDataTask = dbConnection.ReadDataAsync($"SELECT id, password FROM base.users WHERE email ILIKE {identifier} LIMIT 1");
                }
                catch
                {
                    userDataTask = dbConnection.ReadDataAsync($"SELECT id, password FROM base.users WHERE username ILIKE {identifier} LIMIT 1");
                }

                Task <uint> resultTask = userDataTask.ContinueWith((task) =>
                {
                    if (task.IsCompletedSuccessfully)
                    {
                        DbDataReader reader = task.Result;
                        if (reader?.Read() ?? false)
                        {
                            uint userId       = (uint)(int)reader["id"];
                            string dbPassword = (string)reader["password"];
                            if (PasswordUtils.VerifyPassword(password, dbPassword))
                            {
                                return(userId);
                            }
#pragma warning disable CS0618 // We know what we are doing, tryna be good guys
                            else if (PasswordUtils.VerifyPasswordLegacy(password, dbPassword))
#pragma warning restore CS0618
                            {
                                //ALERT!!! LEGACY PASSWORD FOUND!!!!! UPDATE PASSWORD!!!!!!!
                                DatabaseConnection.NewAsyncConnection((dbConnection_) => dbConnection_.ExecuteNonQueryAsync($"UPDATE base.users SET password = {PasswordUtils.HashPassword(password)} WHERE id = {userId}"));

                                return(userId);
                            }
                        }
                    }
                    else if (task.IsFaulted)
                    {
                        UserManager.Logger.Error("Failed to authenicate user", task.Exception);
                    }

                    return(0u);
                });

                Task.WhenAll(resultTask).ContinueWith((task) => dbConnection.Dispose());

                return(resultTask);
            }
            catch
            {
                dbConnection.Dispose();
            }

            return(Task.FromResult(0u));
        }
コード例 #10
0
 public static Task <PlayerUserData> TryCreateNewUserAsync(string username, string password, string email, IPAddress ip) => DatabaseConnection.NewAsyncConnection((dbConnection) => dbConnection.ReadDataAsync($"INSERT INTO base.users(username, password, email, register_ip) VALUES({username}, {PasswordUtils.HashPassword(password)}, {email}, {ip}) RETURNING id, username, permission_rank, name_color, group_name, total_exp, bonus_exp, hats, heads, bodys, feets, current_hat, current_hat_color, current_head, current_head_color, current_body, current_body_color, current_feet, current_feet_color, speed, accel, jump, last_online, '{{}}'::integer[] AS friends, '{{}}'::integer[] AS ignored, '{{}}'::integer[] AS campaign_runs").ContinueWith(UserManager.ParseSqlUserData));