public UserClient Authenticate(string username, string password)
        {
            var checkUsername = _db.User.FirstOrDefault(s => s.Username == username);

            if (checkUsername == null)
            {
                return(null);
            }
            // Check password
            bool validPassword = BCrypt.Net.BCrypt.Verify(password, checkUsername.Password);

            if (!validPassword)
            {
                //return Json(new { status = 400, message = "Username or password invalid" });
                return(null);
            }

            // authentication successful so generate jwt token
            var key = Encoding.ASCII.GetBytes(_appsettings.Secret);

            var token = _blogservice.EndcodeTokenWithJWT(checkUsername, key);

            if (token == null)
            {
                return(null);
            }

            var tokenModifed = myEncodeToken(token);

            UserClient UserNew = new UserClient();

            UserNew.Fullname = checkUsername.Fullname;
            UserNew.Token    = tokenModifed;
            return(UserNew);
        }
        public IActionResult Register([FromForm] User account)
        {
            if (ModelState.IsValid)
            {
                var checkUsername = _db.User.FirstOrDefault(s => s.Username == account.Username);
                if (checkUsername != null)
                {
                    return(Json(new { status = 404, message = "Username is exist" }));
                }
                // hashpassword

                string pwhash = BCrypt.Net.BCrypt.HashPassword(account.Password);
                // new User
                User user = new User();
                user.Fullname = account.Fullname;
                user.Password = pwhash;
                user.Username = account.Username;
                user.RoleID   = 3;
                // Role member
                _db.User.Add(user);
                _db.SaveChanges();

                // authentication successful so generate jwt token
                var key = Encoding.ASCII.GetBytes(_appsettings.Secret);

                var token = _blogservice.EndcodeTokenWithJWT(user, key);

                if (token == null)
                {
                    return(Json(new { status = 500, message = "Server Interval" }));
                }

                var tokenModified = _userService.myEncodeToken(token);

                return(Json(new { status = 200, message = "Create User Complete", fullname = user.Fullname, token = token }));
            }
            return(Json(new { status = 400, message = "Field invalid" }));
        }
Beispiel #3
0
 public string EndcodeTokenWithJWT(User User, byte[] secretKey)
 {
     return(_blogservice.EndcodeTokenWithJWT(User, secretKey));
 }