Example #1
0
        private void HandleSpecificPacket(UserAuthRequest packet)
        {
            logger.LogDebug("Processing UserAuthRequest packet, user='******', service='{Service}', method='{Method}'.", packet.UserName, packet.ServiceName, packet.MethodName);

            // TODO - if this is the first user auth request, send a welcome banner

            if (packet.MethodName == "none")
            {
                SendFail();
            }
            else if (packet.MethodName == "password")
            {
                // See https://tools.ietf.org/html/rfc4252#section-8

                // TODO - HACK - simple auth scheme for testing
                if ((packet.UserName == "foo") && (packet.Password == "bar"))
                {
                    Send(new UserAuthSuccess());
                }
                else
                {
                    SendFail();
                }
            }
            else
            {
                SendFail();
            }
        }
Example #2
0
        public UserAuth ValidateUser(UserAuthRequest userAuthRequest)
        {
            User     user     = new User();
            UserAuth userAuth = new UserAuth();

            using (SqlConnection con = new SqlConnection(securityConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("ValidateUser", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 20).Value = userAuthRequest.userName;
                    cmd.Parameters.Add("@Password", SqlDbType.VarChar, 20).Value = userAuthRequest.password;
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())
                    {
                        user.id          = Convert.ToInt16(reader["Id"].ToString());
                        user.userName    = reader["UserName"].ToString();
                        user.firstName   = reader["firstName"].ToString();
                        user.email       = reader["Email"].ToString();
                        user.permissions = reader["Permissions"].ToString();
                    }
                }
                con.Close();
            }

            if (user.userName != null)
            {
                // Build User Security Object
                userAuth = BuildUserAuthObject(user);
            }
            return(userAuth);
        }
        public async Task <User> ValidateUserCredentialsAsync(UserAuthRequest userAuthRequest)
        {
            var parameters = new DynamicParameters();

            parameters.Add("@UserName", userAuthRequest.UserName);
            parameters.Add("@Password", userAuthRequest.Password);
            var user = await _dapper.GetAsync <User>(StoredProc.GetUserByLoginCredential, parameters);

            return(user);
        }
Example #4
0
        public NullUserAuthResponse(UserAuthRequest uar)
        {
            UserId   = uar.UserId;
            UserName = $@"Misaka-{uar.UserId}";
            Rank     = (int)(uar.UserId % 10);
            Random rng = new Random((int)uar.UserId);

            Colour      = new Colour(rng.Next());
            Permissions = (UserPermissions)rng.Next();
        }
        public async Task <string> AuthenticateUserAsync(UserAuthRequest authRequest)
        {
            var user = await _userRepository.ValidateUserCredentialsAsync(authRequest);

            if (user != null)
            {
                return(GenerateJsonWebToken(user));
            }

            return(null);
        }
        public async Task <IActionResult> Login([FromBody] UserAuthRequest user)
        {
            if (ModelState.IsValid)
            {
                var existingUser = await _userManager.FindByEmailAsync(user.Email);

                if (existingUser == null)
                {
                    return(BadRequest(new AuthResult()
                    {
                        Result = false,
                        Errors = new List <string>()
                        {
                            "Invalid login request"
                        }
                    }));
                }

                var isCorrect = await _userManager.CheckPasswordAsync(existingUser, user.Password);

                if (isCorrect)
                {
                    var jwtToken = GenerateJwtToken(existingUser);

                    return(Ok(new AuthResult()
                    {
                        Result = true,
                        Token = jwtToken
                    }));
                }
                else
                {
                    return(BadRequest(new AuthResult()
                    {
                        Result = false,
                        Errors = new List <string>()
                        {
                            "Invalid login request"
                        }
                    }));
                }
            }

            return(BadRequest(new AuthResult()
            {
                Result = false,
                Errors = new List <string>()
                {
                    "Invalid payload"
                }
            }));
        }
Example #7
0
        public void AttemptAuth(UserAuthRequest request, Action <IUserAuthResponse> onSuccess, Action <Exception> onFailure)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

#if DEBUG
            if (request.UserId >= 10000)
            {
                onSuccess.Invoke(new MisuzuUserAuthResponse {
                    Success       = true,
                    UserId        = request.UserId,
                    UserName      = @"Misaka-" + (request.UserId - 10000),
                    ColourRaw     = (RNG.Next(0, 255) << 16) | (RNG.Next(0, 255) << 8) | RNG.Next(0, 255),
                    Rank          = 0,
                    SilencedUntil = DateTimeOffset.MinValue,
                    Permissions   = UserPermissions.SendMessage | UserPermissions.EditOwnMessage | UserPermissions.DeleteOwnMessage,
                });
                return;
            }
#endif
            MisuzuUserAuthRequest mar = new MisuzuUserAuthRequest(request);

            HttpRequestMessage req = new HttpRequestMessage(HttpRequestMessage.POST, DataProvider.GetURL(URL));
            req.SetHeader(@"X-SharpChat-Signature", DataProvider.GetSignedHash(mar));
            req.SetBody(JsonSerializer.SerializeToUtf8Bytes(mar));

            HttpClient.SendRequest(
                req,
                onComplete: (t, r) => {
                using MemoryStream ms = new MemoryStream();
                r.Body.CopyTo(ms);
                MisuzuUserAuthResponse res = JsonSerializer.Deserialize <MisuzuUserAuthResponse>(ms.ToArray());
                if (res.Success)
                {
                    onSuccess.Invoke(res);
                }
                else
                {
                    onFailure.Invoke(new UserAuthFailedException(res.Reason));
                }
            },
                onError: (t, e) => {
                Logger.Write(@"An error occurred during authentication.");
                Logger.Debug(e);
                onFailure.Invoke(e);
            }
                );
        }
        public async Task <ActionResult <UserAuthResponse> > AuthUser(UserAuthRequest request)
        {
            var user = await _context.Users.Include(u => u.auth).Where(u => u.email == request.email).SingleOrDefaultAsync();

            if (user == null || !BC.Verify(request.password, user.auth.password))
            {
                return(null);
            }
            else
            {
                var token = UserAuthHelper.generateJwtToken(user);
                return(new UserAuthResponse(user, token));
            }
        }
Example #9
0
        public async Task <IActionResult> SignIn([FromBody] UserAuthRequest userAuth)
        {
            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid properties.");
                return(BadRequest());
            }

            if (!await _auth.ValidateUser(userAuth))
            {
                return(Forbid());
            }

            return(Ok());
        }
Example #10
0
        public async Task <bool> ValidateUser(UserAuthRequest userAuth)
        {
            var user = await _userRepository.GetByUserName(userAuth.UserName);

            if (user == null)
            {
                return(false);
            }
            // check password
            var hashedPassword = await _hashService.HashText(userAuth.Password);

            if (hashedPassword.Equals(user.Password) == false)
            {
                return(false);
            }
            return(true);
        }
Example #11
0
        protected async Task <string> GetAccessToken()
        {
            if (userRepository != null)
            {
                if (userRepository.LastLogin.AddSeconds(userRepository.TokenTime) > DateTime.Now.AddSeconds(120))
                {
                    return(userRepository.AccessToken);
                }
                else
                {
                    TokenRefreshRequest tokenRefreshRequest = new TokenRefreshRequest
                    {
                        refreshToken = userRepository.RefreshToken,
                    };
                    var res = await _xlinkApi.postUserTokenRefresh(tokenRefreshRequest, userRepository.AccessToken);

                    userRepository.AccessToken  = res.accessToken;
                    userRepository.TokenTime    = int.Parse(res.expireIn);
                    userRepository.LastLogin    = DateTime.Now;
                    userRepository.RefreshToken = res.refreshToken;

                    return(userRepository.AccessToken);
                }
            }
            else
            {
                UserAuthRequest userAuthRequest = new UserAuthRequest
                {
                };
                var res = await _xlinkApi.postUserAuth(userAuthRequest);

                userRepository = new UserRepository
                {
                    AccessToken  = res.accessToken,
                    TokenTime    = res.expireIn,
                    LastLogin    = DateTime.Now,
                    RefreshToken = res.refreshToken,
                };

                return(userRepository.AccessToken);
            }
        }
        public IActionResult CheckUser([FromForm] UserAuthRequest request)
        {
            var tags = new [] { "administrator", "management" };

            try
            {
                var userlog = string.Format("user : {0}, password : {1}", request.UserName, request.Password);
                _logger.LogInformation(userlog);

                if (request.UserName == "authuser") //Sample check you can put your custom logic over here
                {
                    return(AuthResult.Deny());
                }
            }
            catch (Exception ex)
            {
                //check or log error
            }

            return(AuthResult.Allow(tags));
        }
Example #13
0
        public async Task <IActionResult> LoginAsync([FromBody] UserAuthRequest userAuthRequest)
        {
            IActionResult response = Unauthorized();

            try
            {
                var jwtToken = await _authenticationService.AuthenticateUserAsync(userAuthRequest);

                if (!string.IsNullOrEmpty(jwtToken))
                {
                    return(Ok(new { token = jwtToken }));
                }
            }
            catch (Exception ex)
            {
                //Log exception here
                return(BadRequest("OOPS! Something went wrong while processing your request. Please try again"));
            }

            return(response);
        }
        public async Task <IActionResult> Register([FromBody] UserAuthRequest user)
        {
            if (ModelState.IsValid)
            {
                var existingUser = await _userManager.FindByEmailAsync(user.Email);

                if (existingUser != null)
                {
                    return(BadRequest(new AuthResult()
                    {
                        Result = false,
                        Errors = new List <string>()
                        {
                            "Email already exists"
                        }
                    }));
                }

                var newUser = new ApplicationUser()
                {
                    UserName = user.Email,
                    Email    = user.Email,
                };

                var isCreated = await _userManager.CreateAsync(newUser, user.Password);

                if (isCreated.Succeeded)
                {
                    var token = GenerateJwtToken(newUser);

                    var id = _userManager.GetUserId(User);
                    await _categoryRepository.AddAsync(new Category { Name = "Default", Description = "Default category" }, newUser.Id);

                    await _categoryRepository.SaveAsync();

                    return(Ok(new AuthResult()
                    {
                        Result = true,
                        Token = token
                    }));
                }

                return(new JsonResult(new AuthResult()
                {
                    Result = false,
                    Errors = isCreated.Errors.Select(x => x.Description).ToList()
                })
                {
                    StatusCode = 500
                });
            }

            return(BadRequest(new AuthResult()
            {
                Result = false,
                Errors = new List <string>()
                {
                    "Invalid payload"
                }
            }));
        }
Example #15
0
        public async Task <IActionResult> AuthenticateAsync([FromBody] UserAuthRequest userDto, CancellationToken cancellationToken = default)
        {
            UserDto user = await _userService.AuthenticateAsync(userDto.Username, userDto.Password);

            return(SendToken(user));
        }
Example #16
0
 public MisuzuUserAuthRequest(UserAuthRequest uar)
 {
     AuthRequest = uar ?? throw new ArgumentNullException(nameof(uar));
 }
Example #17
0
        public async Task <IActionResult> RegisterAsync([FromBody] UserAuthRequest authRequest, CancellationToken cancellationToken = default)
        {
            var user = await _userService.RegisterAsync(authRequest.Username, authRequest.Password);

            return(SendToken(user));
        }
Example #18
0
 public void AttemptAuth(UserAuthRequest request, Action <IUserAuthResponse> onSuccess, Action <Exception> onFailure)
 {
     if (request.Token.StartsWith(@"FAIL:"))
     {
         onFailure.Invoke(new UserAuthFailedException(request.Token[5..]));