Example #1
0
        public IActionResult Login([FromBody] LoginUserResource loginUserResource)
        {
            var user = mapper.Map <LoginUserResource, User>(loginUserResource);

            var userEmail = unitOfWork.Accounts.FindUserByEmail(user.Email);

            if (userEmail == null)
            {
                return(NotFound(new ApiResponse(404, "User not found")));
            }

            var hashedPassword = userEmail.Password;

            if (!SecurePasswordHasherHelper.Verify(user.Password, hashedPassword))
            {
                return(Unauthorized(new ApiResponse(401, "Username or password don't match")));
            }

            var token = unitOfWork.Accounts.Login(user, _auth);

            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                expires_in = token.ExpiresIn,
                token_type = token.TokenType,
                creation_Time = token.ValidFrom,
                expiration_Time = token.ValidTo,
                user_Id = userEmail.Id,
                user_name = userEmail.Name,
                user_image = userEmail.ImageUrl
            }));
        }
        public ActionResult Login(UserDTO userDTO, string ReturnUrl)
        {
            UserDTO userDetails = utilisateurLogic.GetUserByMail(userDTO.Email);

            if (userDetails == null)
            {
                userDTO.LoginErrorMessage = "Aucun compte n'a été trouvé avec cette addresse";
                return(View("Login", userDTO));
            }
            else if (SecurePasswordHasherHelper.Verify(userDTO.Password, userDetails.Password) == false)
            {
                userDTO.LoginErrorMessage = "Vérifiez vos identifiants";
                return(View("Login", userDTO));
            }
            else
            {
                Session["userID"]    = userDetails.Id;
                Session["firstname"] = userDetails.Firstname;
                Session["lastName"]  = userDetails.Lastname;
                Session["userJob"]   = userDetails.Job;

                Session["notifs"] = notifLogic.ListAllForUser(userDetails.Id).FindAll(n => n.IsRead == 0).Count;

                FormsAuthentication.SetAuthCookie(userDetails.Email, false);
                return(Redirect("/"));
            }
        }
 public void SecurePasswordHasherHelper_Verify_NotSupportedExceptionWasThrown_Fail()
 {
     Assert.Throws <NotSupportedException>(() =>
     {
         SecurePasswordHasherHelper.Verify("test", "test");
     });
 }
        public IActionResult Login([FromBody] Usuario usuario)
        {
            var usuarioEmail = _dashboardDbContext.Usuarios.FirstOrDefault(u => u.Email == usuario.Email);

            if (usuarioEmail == null)
            {
                return(NotFound());
            }
            if (!SecurePasswordHasherHelper.Verify(usuario.Senha, usuarioEmail.Senha))
            {
                return(Unauthorized());
            }
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, usuario.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, usuario.Email),
                new Claim(ClaimTypes.Name, usuario.Email),
            };
            var token = _auth.GenerateAccessToken(claims);

            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                expires_in = token.ExpiresIn,
                token_type = token.TokenType,
                creation_Time = token.ValidFrom,
                expiration_Time = token.ValidTo,
                user_id = usuarioEmail.Id,
                user_name = usuarioEmail.Nome,
                user_email = usuario.Email,
            }));
        }
        public IActionResult Login([FromBody] Usuario usuario)
        {
            //usando o LINQ para fazer a consulta no email do usuário
            var userEmail = _svtaDbContext.Usuarios.FirstOrDefault(u => u.Email == usuario.Email);

            if (userEmail == null)
            {
                return(NotFound());
            }
            //verifica se o hash na senha do usuario é falso
            if (!SecurePasswordHasherHelper.Verify(usuario.Senha, userEmail.Senha))
            {
                return(Unauthorized());
            }
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Email, usuario.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Email, usuario.Email),
            };
            var token = _auth.GenerateAccessToken(claims);

            //conteúdo que será retorno ao fazermos nossa requisição da API, essa requisições serão utilizadas no projeto do app para exibir nome do usuário
            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                expires_in = token.ExpiresIn,
                token_type = token.TokenType,
                creation_Time = token.ValidFrom,
                expiration_Time = token.ValidTo,
                user_id = userEmail.Id,
                user_nome = userEmail.Nome,
                user_email = userEmail.Email
            }));
        }
Example #6
0
        public async Task <IActionResult> Login(User user)
        {
            var userEmail = _dbContext.Users.FirstOrDefault(u => u.Email == user.Email);

            if (userEmail == null)
            {
                return(StatusCode(StatusCodes.Status404NotFound));
            }
            var hashedPassword = userEmail.Password;

            if (!SecurePasswordHasherHelper.Verify(user.Password, hashedPassword))
            {
                return(Unauthorized());
            }
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(ClaimTypes.Name, user.Email)
            };

            var token = _auth.GenerateAccessToken(claims);

            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                expires_in = token.ExpiresIn,
                token_type = token.TokenType,
                creation_Time = token.ValidFrom,
                expiration_Time = token.ValidTo,
                user_Id = userEmail.Id
            }));
        }
Example #7
0
        public /*async Task<IActionResult>*/ IActionResult Login(User objUser)
        {
            User user = null;

            if (ModelState.IsValid)
            {
                // var obj = _context.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.Password)).FirstOrDefault();
                if (use_test_repository)
                {
                    foreach (User item in _repository.GetAllItems())
                    {
                        if (item.username == objUser.username)
                        {
                            user = item;
                        }
                    }
                }

                else
                {
                    user = /*await*/ _context.User.FirstOrDefault/*Async*/ (m => m.username == objUser.username);
                }
                if (user != null)
                {
                    if (SecurePasswordHasherHelper.Verify(objUser.encrypted_password, user.encrypted_password))
                    {
                        logged_user = user;
                        return(RedirectToAction("Dashboard", logged_user));// new User(user.name,user.username,user.encrypted_password));
                    }
                }
            }
            return(View("Login", objUser));
        }
Example #8
0
        public IActionResult ChangePassword(ChangePasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userEmail = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
            var user      = _dbContext.Users.FirstOrDefault(u => u.Email == userEmail);

            if (user == null)
            {
                return(NotFound());
            }

            var hashedPassword = user.Password;

            if (!SecurePasswordHasherHelper.Verify(model.OldPassword, hashedPassword))
            {
                return(BadRequest("You can't change the password"));
            }
            user.Password = SecurePasswordHasherHelper.Hash(model.NewPassword);
            _dbContext.SaveChanges();
            return(Ok("Your password has been changed"));
        }
        public IActionResult Login([Bind("UserId", "Email", "Password")] UserModel login)
        {
            if (login.Email == null || login.Password == null)
            {
                return(View());
            }

            string Email = login.Email;
            //find user in database
            var user = new_db.findUser(Email);

            if (user == null)
            {
                return(View("Register"));
            }
            string userPassword = user.Password;

            if (SecurePasswordHasherHelper.Verify(login.Password, userPassword))
            {
                HttpContext.Session.SetInt32("ID", user.UserId);
                sessionState = true;
                admin        = user.Admin;
                userId       = user.UserId;
                //Console.WriteLine("id" + user.UserId);
                return(Redirect("../Home/"));
            }
            return(View());
        }
Example #10
0
        public IActionResult AdminLogin(ADMINMast ADMINMast)
        {
            var UserName = _dbContext.ADMINMast.FirstOrDefault(a => a.UserName == a.UserName);

            if (UserName == null)
            {
                return(StatusCode(StatusCodes.Status404NotFound));
            }
            var hashedPassword = UserName.Password;

            if (!SecurePasswordHasherHelper.Verify(ADMINMast.Password, hashedPassword))
            {
                return(Unauthorized());
            }
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, ADMINMast.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Name, ADMINMast.UserName),
            };

            var token = _auth.GenerateAccessToken(claims);

            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                token_type = token.TokenType,
                Admin_Id = ADMINMast.AdminID,
                user_name = ADMINMast.UserName,
                expires_in = token.ExpiresIn,
                creation_Time = token.ValidFrom,
                expiration_Time = token.ValidTo,
            }));
        }
Example #11
0
        public IActionResult Login([FromBody] User user)
        {
            var userEmail = _dbContext.Users.FirstOrDefault(u => u.Email == user.Email);

            if (userEmail == null)
            {
                return(NotFound());
            }
            if (!SecurePasswordHasherHelper.Verify(user.Password, userEmail.Password))
            {
                return(Unauthorized());
            }
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.Role, userEmail.Role)
            };
            var token = _auth.GenerateAccessToken(claims);

            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                expires_in = token.ExpiresIn,
                token_type = token.TokenType,
                creation_Time = token.ValidFrom,
                expiration_Time = token.ValidTo,
                user_id = userEmail.Id
            }));
        }
 public static bool PasswordMatch(string DBPass, string Pass)
 {
     if (SecurePasswordHasherHelper.Verify(Pass, DBPass))
     {
         return(true);
     }
     return(false);
 }
Example #13
0
        public async Task <bool> Login(LoginDto input)
        {
            var user = await _userRepository.GetAll()
                       .FirstOrDefaultAsync(x => x.Username == input.Username);

            if (user == null)
            {
                return(false);
            }
            var decodedPassword = SecurePasswordHasherHelper.Verify(input.Password, user.Password);

            return(decodedPassword);
        }
        public IActionResult TrocarSenha([FromBody] ChangePasswordModel changepasswordModel)
        {
            var userEmail = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
            var user      = _dashboardDbContext.Usuarios.FirstOrDefault(u => u.Email == userEmail);

            if (user == null)
            {
                return(NotFound());
            }

            if (!SecurePasswordHasherHelper.Verify(changepasswordModel.OldPassword, user.Senha))
            {
                return(Unauthorized("Me desculpe você não pode alterar sua senha"));
            }
            user.Senha = SecurePasswordHasherHelper.Hash(changepasswordModel.NewPassword);
            _dashboardDbContext.SaveChanges();
            return(Ok("Sua senha foi alterada com sucesso!"));
        }
        public IActionResult ChangePassword([FromBody] ChangePasswordModel changePasswordModel)
        {
            var userEmail = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
            var user      = _cWheelsDbContext.Users.FirstOrDefault(u => u.Email == userEmail);

            if (user == null)
            {
                return(NotFound());
            }

            if (!SecurePasswordHasherHelper.Verify(changePasswordModel.OldPassword, user.Password))
            {
                return(Unauthorized("Sorry you can't change the password"));
            }
            user.Password = SecurePasswordHasherHelper.Hash(changePasswordModel.NewPassword);
            _cWheelsDbContext.SaveChanges();
            return(Ok("Your password has been changed"));
        }
Example #16
0
        public async Task <IActionResult> Login(User objUser)
        {
            if (ModelState.IsValid)
            {
                var user = await _context.User.FirstOrDefaultAsync(m => m.username == objUser.username);

                if (user != null)
                {
                    if (SecurePasswordHasherHelper.Verify(objUser.encrypted_password, user.encrypted_password))
                    {
                        logged_user = user;
                    }

                    return(RedirectToAction("Dashboard", logged_user));
                }
            }
            ViewBag.Message = string.Format("Incorrect username or password");
            return(View("Login", objUser));
        }
        public IActionResult TrocarSenha([FromBody] TrocarSenha trocarSenha)
        {
            var usuarioEmail = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
            var usuario      = _svtaDbContext.Usuarios.FirstOrDefault(u => u.Email == usuarioEmail);

            if (usuario == null)
            {
                return(NotFound("Usuario não encontrado"));
            }
            if (!SecurePasswordHasherHelper.Verify(trocarSenha.SenhaAntiga, usuario.Senha))
            {
                return(Unauthorized("Desculpe, mas você não pode trocar sua senha"));
            }

            usuario.Senha = SecurePasswordHasherHelper.Hash(trocarSenha.NovaSenha);
            _svtaDbContext.SaveChanges();

            return(Ok("Sua senha foi alterada com sucesso"));
        }
Example #18
0
        public IActionResult Login([FromBody] User user)
        {
            // get the user from the db
            var userEmail = _dbContext.User.Where(u => u.Email == user.Email).SingleOrDefault();


            // if user was not found, return notFound
            if (userEmail == null)
            {
                return(NotFound());
            }

            // if plaintext password doesn't match hashed password, return unauthorized
            if (!SecurePasswordHasherHelper.Verify(user.Password, userEmail.Password))
            {
                return(Unauthorized());
            }

            // otherwise, generate JWT Token

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(ClaimTypes.Email, user.Email),

                // add role metadata to claim so it can be used for authorization for each request
                new Claim(ClaimTypes.Role, userEmail.Role)
            };

            var token = _auth.GenerateAccessToken(claims);

            // return token to the client
            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                expires_in = token.ExpiresIn,
                token_type = token.TokenType,
                creation_time = token.ValidFrom,
                expiration_time = token.ValidTo,
                user_id = userEmail.Id
            }));
        }
Example #19
0
        public async Task <IActionResult> Validate(Staff staff)
        {
            if (staff == null)
            {
                return(NotFound());
            }

            Staff _staff = await UserManager.FindByEmailAsync(staff.Email).ConfigureAwait(false);

            if (_staff != null)
            {
                if (SecurePasswordHasherHelper.Verify(staff.Password, _staff.Password))
                {
                    try
                    {
                        await SignInManager.PasswordSignInAsync(_staff, _staff.Password, false, false).ConfigureAwait(false);

                        return(Json(new
                        {
                            status = true,
                            message = "Login Successful!",
                            isAdmin = await UserManager.IsInRoleAsync(_staff, "Admin").ConfigureAwait(false)
                        }));
                    }
                    catch (Exception e)
                    {
                        return(Json(new { status = false, message = "Error: " + e.Message }));

                        throw;
                    }
                }
                else
                {
                    return(Json(new { status = false, message = "Invalid Password!" }));
                }
            }
            else
            {
                return(Json(new { status = false, message = "Invalid Email!\n" }));
            }
        }
Example #20
0
        public async Task <(bool, string, object)> Login(UserLoginDto userLoginDto)
        {
            try
            {
                var userExists = await _cinemaDbContext.User.Where(user => user.Email.Equals(userLoginDto.Email)).SingleOrDefaultAsync();

                if (userExists == null)
                {
                    return(false, "User Not Found !!", null);
                }

                if (!SecurePasswordHasherHelper.Verify(userLoginDto.Password, userExists.Password))
                {
                    return(false, "UnAuthenticated User !!", null);
                }

                var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Email, userExists.Email),
                    new Claim(ClaimTypes.Email, userExists.Email),
                    new Claim(ClaimTypes.Role, userExists.Role)
                };

                var token = _auth.GenerateAccessToken(claims);

                var result = new
                {
                    access_token    = token.AccessToken,
                    expires_in      = token.ExpiresIn,
                    token_type      = token.TokenType,
                    creation_Time   = token.ValidFrom,
                    expiration_Time = token.ValidTo,
                    user_id         = userExists.Id
                };

                return(true, string.Empty, result);
            }
            catch (Exception x)
            {
                return(false, x.InnerException?.Message ?? x.Message, null);
            }
        }
Example #21
0
        public async Task <bool> ChangePassword(ChangePasswordDto input)
        {
            var user = await _userRepository.GetByIdAsync(input.UserId);

            if (user == null)
            {
                throw new Exception("Kullanici bulunamadi");
            }
            var decodedPassword = SecurePasswordHasherHelper.Verify(input.OldPassword, user.Password);

            if (!decodedPassword)
            {
                throw new Exception("Eski sifre yanlis");
            }
            var hashedPassword = SecurePasswordHasherHelper.Hash(input.NewPassword);

            user.Password = hashedPassword;
            await _userRepository.UpdateAsync(user);

            return(true);
        }
Example #22
0
        public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordResource changePasswordResource)
        {
            var userEmail = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
            var user      = unitOfWork.Accounts.FindUserByEmail(userEmail);

            if (user == null)
            {
                return(NotFound(new ApiResponse(404, "User not found")));
            }

            var hashedPassword = user.Password;

            if (!SecurePasswordHasherHelper.Verify(changePasswordResource.OldPassword, hashedPassword))
            {
                return(BadRequest(new ApiResponse(400, "Enter correct old password")));
            }

            user.Password = SecurePasswordHasherHelper.Hash(changePasswordResource.NewPassword);
            await unitOfWork.CompleteAsync();

            return(Ok(new ApiResponse(200, "Password changed successfully")));
        }
        public IActionResult ChangePassword([FromBody] ChangePassword changePassword)
        {
            var userEmail = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
            var user      = _dataContext.UserTbl.FirstOrDefault(u => u.Email == userEmail);

            if (user == null)
            {
                return(NotFound());
            }

            //ita passe dena old password ekai user eke tina password eki same da kiyala balanawa.
            if (!SecurePasswordHasherHelper.Verify(changePassword.OldPassword, user.Password))
            {
                return(Unauthorized("Sorry you can't change the password"));
                //login wenakota tinan ekama change karala ganna puluwan
            }

            //ita passe body eke tina new password eka user ge password eka witdihata add wenna one.
            user.Password = SecurePasswordHasherHelper.Hash(changePassword.NewPassword);
            _dataContext.SaveChanges();
            return(Ok("your password has been changed!"));
        }
        public IActionResult Login(User user)
        {
            var userEmail = _dbContext.Users.FirstOrDefault(u => u.Email == user.Email); //Verifica se existe o email no banco de dados

            if (userEmail == null)
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));
            }
            var hashedPassword = userEmail.Password;

            if (!SecurePasswordHasherHelper.Verify(user.Password, hashedPassword)) //Verifica se a senha informada é igual a senha do banco de dados protegida por hash
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));             // retorna Status401Unauthorized quando a senha for diferente
            }
            //Cria uma objeto claim para transmitir as informações com segurança.
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(ClaimTypes.Name, user.Email),
                new Claim(ClaimTypes.Role, userEmail.Role)
            };
            //Retorna o objeto que contém o acesso token e todas as outras informações para o usuário.
            var token = _auth.GenerateAccessToken(claims);

            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                token_type = token.TokenType,
                user_Id = userEmail.Id,
                user_name = userEmail.Name,
                expires_in = token.ExpiresIn,
                creation_Time = token.ValidFrom,
                expiration_Time = token.ValidTo,
                roles_user = userEmail.Role,
            }));
        }
         public IActionResult Login([Bind("UserId", "Email", "Password")]UserModel login)
        {
            if (login.Email == null || login.Password == null) 
                return View();

            string Email = login.Email;
            var user = _db.Users.FirstOrDefault(p => p.Email == Email);

            if (user == null)
                return View("Register");
            
            string userPassword = user.Password;
            
            if(SecurePasswordHasherHelper.Verify(login.Password,userPassword))
            {
                HttpContext.Session.SetInt32("ID", user.UserId);
                sessionState = true;
                role = user.Role;
                userId = user.UserId;
                return Redirect("../Home/");
            }
            return View();
        }
Example #26
0
        public async Task <TenantLoginDto> Login(TenantOrEducatorLoginDto input)
        {
            var user = await _tenantRepository.GetAll()
                       .FirstOrDefaultAsync(x => x.Email == input.Email);

            if (user == null)
            {
                throw new Exception("There is no user!");
            }
            var decodedPassword = SecurePasswordHasherHelper.Verify(input.Password, user.Password);

            if (!decodedPassword)
            {
                return(null);
            }

            var result = new TenantLoginDto
            {
                Id = user.Id, EntityType = EntityType.Tenant, TenantName = user.TenantName
            };

            return(result);
        }
Example #27
0
        public IActionResult Login([FromBody] User user)
        {
            var userEmail = _dbContext.Users.FirstOrDefault(u => u.Email == user.Email);

            if (userEmail == null)
            {
                return(NotFound());
            }

            //And to validate the password you need to add the following line of code.
            //first parameter is the password provided by user in plain text
            //second parameter is the hashed password retrieved from the db
            if (!SecurePasswordHasherHelper.Verify(user.Password, userEmail.Password))
            {
                return(Unauthorized());
            }
            //if login a user with admin role, will return admin token
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.Role, userEmail.Role),//get the role value from db
            };
            //this line will generate access token
            var token = _auth.GenerateAccessToken(claims);

            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                expires_in = token.ExpiresIn,//you can remove the remaining if you only want to return token type
                token_type = token.TokenType,
                creation_Time = token.ValidFrom,
                expiration_Time = token.ValidTo,
                user_id = userEmail.Id
            }));
        }
        public IActionResult Login([FromBody] User user)
        {
            var userEmail = _dataContext.UserTbl.FirstOrDefault(u => u.Email == user.Email);

            if (userEmail == null)
            {
                return(NotFound());
            }
            //password eka check karana eka
            if (!SecurePasswordHasherHelper.Verify(user.Password, userEmail.Password))
            {
                return(Unauthorized());
                //methanadi not found newe unauthorized danna one mokada password wadradi kiyanne
                //unauthorized kenek thami log wenne hinda.
            }

            //jwt token eka thama danna one
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(ClaimTypes.Email, user.Email),
            };

            var token = _auth.GenerateAccessToken(claims);

            //json eke pennanna one tika pennanne meke me widihata
            return(new ObjectResult(new
            {
                access_token = token.AccessToken,
                expires_in = token.ExpiresIn,
                token_type = token.TokenType,
                creation_Time = token.ValidFrom,
                expiration_Time = token.ValidTo,
                user_id = userEmail.Id
            }));
        }
Example #29
0
        public static async Task <object> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = null)]
            HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string token = req.Headers.Authorization.ToString();

            if (!AuthorizationHelper.Authorized(token, new string[] { Role.Employee, Role.Manager, Role.Owner }))
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Unauthorized!"));
            }

            //We retrieve the userName field, which comes as a parameter to the function, by deserializing req.Content.
            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            string email   = data.email;
            string oldPass = data.oldPassword;
            string newPass = data.newPassword;

            newPass = SecurePasswordHasherHelper.Hash(newPass);

            try
            {
                //We get the Connection String in the Function App Settings section we defined.
                var str = Environment.GetEnvironmentVariable("sqldb_connection");

                using (SqlConnection connection = new SqlConnection(str))
                {
                    connection.Open();
                    SqlTransaction sqlTran = connection.BeginTransaction();
                    SqlCommand     command = connection.CreateCommand();
                    command.Transaction = sqlTran;
                    try
                    {
                        command.CommandText = @"SELECT PasswordHash FROM Users WHERE email = @email";
                        command.Parameters.AddWithValue("@email", email);

                        string verifyPass = "";
                        using (SqlDataReader oReader = command.ExecuteReader())
                        {
                            while (oReader.Read())
                            {
                                verifyPass = oReader["PasswordHash"].ToString();
                            }
                        }

                        if (!SecurePasswordHasherHelper.Verify(oldPass, verifyPass))
                        {
                            return(req.CreateResponse(HttpStatusCode.NotAcceptable, "Incorrect Password!"));
                        }

                        command.CommandText = @"UPDATE Users " +
                                              "SET PasswordHash = @NewPassword " +
                                              "WHERE email = @email";
                        command.Parameters.AddWithValue("@email", email);
                        command.Parameters.AddWithValue("@NewPassword", newPass);
                        command.ExecuteNonQuery();

                        sqlTran.Commit();
                        connection.Close();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        try
                        {
                            // Attempt to roll back the transaction.
                            sqlTran.Rollback();
                            return(req.CreateResponse(HttpStatusCode.BadRequest, "Rollback!"));
                        }
                        catch (Exception exRollback)
                        {
                            // Throws an InvalidOperationException if the connection
                            // is closed or the transaction has already been rolled
                            // back on the server.
                            Console.WriteLine(exRollback.Message);
                            return(req.CreateResponse(HttpStatusCode.BadRequest, "Rollback exception!"));
                        }
                    }
                }

                return(req.CreateResponse(HttpStatusCode.OK, "Success"));
            }
            catch
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Something went wrong!"));
            }
        }
Example #30
0
        public static async Task <object> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
            HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            User userInfo = new User();
            //We retrieve the userName field, which comes as a parameter to the function, by deserializing req.Content.
            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data     = JsonConvert.DeserializeObject(jsonContent);
            string  email    = data.email;
            string  Password = data.Password;

            //If there is no username, we return the error message
            try
            {
                //We get the Connection String in the Function App Settings section we defined.
                var    str      = Environment.GetEnvironmentVariable("sqldb_connection");
                string holdPass = null;
                using (SqlConnection connection = new SqlConnection(str))
                {
                    string text = @"SELECT U.*, B.roomId FROM Users U " +
                                  "INNER JOIN BranchTable B ON U.branchID = B.branchID " +
                                  "WHERE U.email = @email";

                    SqlCommand command = new SqlCommand(text, connection);

                    command.Parameters.AddWithValue("@email", email);
                    connection.Open();

                    using (SqlDataReader oReader = command.ExecuteReader())
                    {
                        while (oReader.Read())
                        {
                            userInfo.UserID    = oReader["UserID"].ToString();
                            userInfo.roles     = oReader["Role"].ToString();
                            userInfo.email     = oReader["email"].ToString();
                            userInfo.Firstname = oReader["Firstname"].ToString();
                            userInfo.Lastname  = oReader["Lastname"].ToString();
                            userInfo.Position  = oReader["Position"].ToString();
                            userInfo.branchID  = oReader["branchID"].ToString();
                            userInfo.CompanyID = oReader["CompanyID"].ToString();
                            userInfo.roomId    = oReader["roomId"].ToString();
                            holdPass           = oReader["PasswordHash"].ToString();
                        }
                        connection.Close();
                    }
                }

                if (holdPass != null && SecurePasswordHasherHelper.Verify(Password, holdPass))
                {
                    log.LogInformation("MATCH");
                    var token = new JwtBuilder()
                                .WithAlgorithm(new HMACSHA256Algorithm())
                                .WithSecret(Environment.GetEnvironmentVariable("Secret"))
                                .AddClaim("exp", DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds())
                                .AddClaim("UserID", userInfo.UserID)
                                .AddClaim("email", userInfo.email)
                                .AddClaim("Firstname", userInfo.Firstname)
                                .AddClaim("Lastname", userInfo.Lastname)
                                .AddClaim("Position", userInfo.Position)
                                .AddClaim("branchID", userInfo.branchID)
                                .AddClaim("CompanyID", userInfo.CompanyID)
                                .AddClaim("roomId", userInfo.roomId)
                                .AddClaim("roles", userInfo.roles)
                                .Build();
                    userInfo.Token = token;
                    return(req.CreateResponse(HttpStatusCode.OK, userInfo));
                }
                else
                {
                    log.LogInformation("NO MATCH");
                    return(req.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Credentials"));
                }
            }
            catch
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "Something went wrong!"));
            }
        }