Esempio n. 1
0
        public ActionResult Get()
        {
            UserWalletAppService userWalletAppService = new UserWalletAppService();
            UserAuthResponse     _apiResponse         = new UserAuthResponse();

            try
            {
                // GET SESSIONS
                SessionController sessionController = new SessionController();
                TblUserAuth       userAuth          = sessionController.GetSession(HttpContext.Session);

                _apiResponse.UserWallet = userWalletAppService.GetBO(userAuth);

                _apiResponse.HttpStatusCode = "200";
                _apiResponse.Message        = "UserWallet GET";
                _apiResponse.Status         = "Success";
            }
            catch (Exception ex)
            {
                _apiResponse.HttpStatusCode = "500";
                _apiResponse.Message        = ex.Message;
                _apiResponse.Status         = "Error";
            }

            return(Ok(_apiResponse));
        }
Esempio n. 2
0
        public ActionResult Login([FromBody] User user)
        {
            UserAuthResponse response = new UserAuthResponse();

            response.authToken = domain.Login(user);
            response.user      = user;
            addLoginCookie(this.HttpContext, user.UserName);
            return(Ok(response));
        }
Esempio n. 3
0
        public IActionResult Authenticate([FromBody] UserView userParam)
        {
            try
            {
                EFDataContext _dbContext = new EFDataContext();
                UserView      dbUser     = _dbContext.Users
                                           .Where(u => u.EmailId == userParam.EmailId.ToLower() &&
                                                  !u.LockedOut && u.Activated)
                                           .Select(u => new UserView {
                    Id        = u.UserId,
                    EmailId   = u.EmailId,
                    FirstName = u.FirstName,
                    LastName  = u.LastName,
                    Role      = u.UserRole.RoleName,
                    Password  = u.PasswordHash
                })
                                           .FirstOrDefault();
                if (dbUser == null)
                {
                    throw new ApiException("Either username or password is incorrect or user is not activated or locked out");
                }
                string hash = dbUser.Password;
                if (!_userService.VerifyPasswordHash(dbUser, hash, userParam.Password))
                {
                    throw new ApiException("Username or password is incorrect");
                }

                var token = _userService.GenerateToken(dbUser.Id);

                if (token == null)
                {
                    throw new ApiException("Username or password is incorrect");
                }

                var      resp     = new UserAuthResponse();
                UserView userResp = new UserView {
                    Id        = dbUser.Id,
                    EmailId   = dbUser.EmailId,
                    FirstName = dbUser.FirstName,
                    LastName  = dbUser.LastName,
                    Role      = dbUser.Role
                };
                resp.User  = userResp;
                resp.Token = token;

                return(Ok(resp));
            }
            catch (Exception ex)
            {
                if (ex is ApiException)
                {
                    return(BadRequest(new { message = ex.Message }));
                }
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }
        }
Esempio n. 4
0
        public async Task <ActionResult> userLogin([FromBodyAttribute] UserCred user)
        {
            UserAuthResponse result = await this.jwtAuthManager.AuthenticateUser(user.username, user.password);

            if (result != null)
            {
                return(Ok(result));
            }
            else
            {
                return(NotFound());
            }
        }
Esempio n. 5
0
        private IActionResult SendToken(UserDto user)
        {
            //TODO: move to user service
            var    claims        = new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) };
            string tokenString   = _jwtAuthManager.GenerateAccessToken(claims);
            var    userWithToken = new UserAuthResponse
            {
                Id       = user.Id,
                Username = user.Username,
                Token    = tokenString
            };

            return(Ok(userWithToken));
        }
        public UserAuthResponse Invoke()
        {
            ClaimsPrincipal user             = contextAccessor.HttpContext.User;
            var             responseContract = new UserAuthResponse();

            responseContract.EmailAddress    = user.FindFirstValue(JwtClaimTypes.Email);
            responseContract.FirstName       = user.FindFirstValue(JwtClaimTypes.GivenName);
            responseContract.LastName        = user.FindFirstValue(JwtClaimTypes.FamilyName);
            responseContract.IsAuthenticated = user.Identity?.IsAuthenticated ?? false;

            if (responseContract.IsAuthenticated)
            {
                string gravatarId = GenerateGravatarHash(responseContract.EmailAddress);
                responseContract.GravatarUrl = $"https://www.gravatar.com/avatar/{gravatarId}?d=mp";
            }
            return(responseContract);
        }
Esempio n. 7
0
        /// <summary>
        /// https://docs.microsoft.com/pl-pl/xamarin/xamarin-forms/data-cloud/web-services/rest
        /// </summary>
        /// <returns></returns>
        public async Task PostAuthUserAsync()
        {
            var uri      = new Uri(AppConstants.AccountAuthUrl);
            var authUser = new User("adam.nowak", "aaaa");
            var json     = Task.Factory.StartNew(() => JsonConvert.SerializeObject(authUser)).Result;
            var content  = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await client.PostAsync(uri, content);

            if (response.IsSuccessStatusCode)
            {
                string respondContent = await response.Content.ReadAsStringAsync();

                User = JsonConvert.DeserializeObject <UserAuthResponse>(respondContent);
            }
            client.DefaultRequestHeaders.Authorization
                = new AuthenticationHeaderValue("Bearer", User.Token);
        }
Esempio n. 8
0
        public UserAuthResponse Authenticate(UserBO userBO)
        {
            using (var db = new dbWorldCCityContext())
            {
                UserAuthRepository userAuthRepository = new UserAuthRepository();
                TblUserAuth        userAuth           = userAuthRepository.Get(userBO, db);

                UserInfoRepository userInfoRepository = new UserInfoRepository();
                TblUserInfo        userInfo           = userInfoRepository.Get(userAuth, db);

                UserWalletRepository userWalletRepository = new UserWalletRepository();
                List <UserWalletBO>  userWallet           = userWalletRepository.GetBO(userAuth, db);

                UserAuthResponse userAuthResponse = new UserAuthResponse();

                userAuthResponse.UserInfo   = userInfo;
                userAuthResponse.UserWallet = userWallet;
                userAuthResponse.UserAuth   = userAuth;

                return(userAuthResponse);
            }
        }
Esempio n. 9
0
        public UserAuthResponse Get(string login, string password)
        {
            var user = db.Users
                       .Include(u => u.UserProfile)
                       .Include(u => u.Account)
                       .Where(u => u.Login == login && u.Password == password.SHA())
                       .FirstOrDefault();

            if (user != null)
            {
                var result = new UserAuthResponse()
                {
                    ID        = user.ID,
                    BirthDate = user.UserProfile.BirthDate,
                    FullName  = user.UserProfile.FullName,
                    RoleID    = user.UserProfile.RoleID,
                    Amount    = user.Account.Amount
                };
                return(result);
            }
            return(null);
        }
Esempio n. 10
0
        public ActionResult Post([FromBody] UserBO userBO)
        {
            UserAppService   userAppService = new UserAppService();
            UserAuthResponse _apiResponse   = new UserAuthResponse();

            if (ModelState.IsValid)
            {
                try
                {
                    UserAuthResponse userAuthResponse = userAppService.Authenticate(userBO);

                    _apiResponse.UserInfo   = userAuthResponse.UserInfo;
                    _apiResponse.UserWallet = userAuthResponse.UserWallet;

                    // SET SESSIONS
                    SessionController sessionController = new SessionController();
                    sessionController.CreateSession(userAuthResponse, HttpContext.Session);


                    _apiResponse.HttpStatusCode = "200";
                    _apiResponse.Message        = "User successfully authenticated";
                    _apiResponse.Status         = "Success";
                }
                catch (Exception ex)
                {
                    _apiResponse.HttpStatusCode = "500";
                    _apiResponse.Message        = ex.Message;
                    _apiResponse.Status         = "Error";
                }
            }
            else
            {
                _apiResponse.HttpStatusCode = "500";
                _apiResponse.Message        = "Please input the required credentials";
                _apiResponse.Status         = "Error";
            }
            return(Ok(_apiResponse));
        }
Esempio n. 11
0
        public ActionResult <UserAuthResponse> Token(string login, string password)
        {
            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
            {
                return(BadRequest(new { ErrorMessage = "Не указан Логин или Пароль." }));
            }

            var identity = GetIdentity(login, password);

            if (identity == null)
            {
                return(BadRequest(new { ErrorMessage = "Неверный Логин или Пароль." }));
            }

            var signingKey = new SigningSymmetricKey(AuthOptions.KEY);
            var now        = DateTime.UtcNow;

            var jwt = new JwtSecurityToken(
                issuer: AuthOptions.ISSUER,
                audience: AuthOptions.AUDIENCE,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(signingKey.GetKey(), signingKey.SigningAlgorithm));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var user = new UserAuthResponse()
            {
                ID        = identity.GetUserId <int>(),
                BirthDate = identity.GetUserBirthDate(),
                AuthToken = encodedJwt,
                FullName  = identity.Name,
                RoleID    = identity.GetUserRoleId <int>(),
                Amount    = identity.GetUserAmount <double>()
            };

            return(user);
        }
Esempio n. 12
0
 public bool CreateSession([FromBody] UserAuthResponse userAuthResponse, ISession session)
 {
     session.SetString(USER_SESSION, JsonConvert.SerializeObject(userAuthResponse.UserAuth));
     return(true);
 }