Esempio n. 1
0
        public async Task <IActionResult> Login([FromBody] LoginModelRequest loginModel)
        {
            ResultResponseObject <TokenResponse> resultService = new ResultResponseObject <TokenResponse>();
            ApplicationUser appUser = null;

            if (loginModel.GrantType == _grantTypePasswordToken)
            {
                appUser = await HandleUserAuthentication(loginModel, resultService);
            }
            else if (loginModel.GrantType == _grantTypeRefreshToken)
            {
                appUser = await HandleRefreshToken(loginModel, resultService);
            }

            if (appUser == null)
            {
                if (resultService.ErrorMessages == null)
                {
                    resultService.ErrorMessages = new List <KeyValuePair <string, string> >();
                }
            }

            if (resultService.Success)
            {
                TokenResponse tokenResponse = await GenerateJwtToken(appUser);

                resultService.Value = tokenResponse;
            }

            return(Response(resultService));
        }
Esempio n. 2
0
 public static User Map(LoginModelRequest modelRequest)
 {
     return(new User()
     {
         Username = modelRequest.Username,
         Password = modelRequest.Password
     });
 }
Esempio n. 3
0
        public async Task <IActionResult> Authenticate([FromBody] LoginModelRequest modelRequest)
        {
            var(_, isFailure, value, error) = await _authenticationService.Login(modelRequest);

            if (isFailure)
            {
                return(BadRequest(error));
            }
            return(Ok(value));
        }
Esempio n. 4
0
        public async Task InvalidPasswordLogin()
        {
            LoginModelRequest loginModel = new LoginModelRequest
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var userAuthenticateResponse = await HttpClient.PostAsJsonAsync($"api/v1/auth/login", loginModel);

            userAuthenticateResponse.IsSuccessStatusCode.Should().BeFalse();
        }
Esempio n. 5
0
        public IActionResult LoginAct(LoginModelRequest Model)
        {
            //数据验证
            var IsValidStr = ValidatetionMethod.IsValid(Model);

            if (!IsValidStr.IsVaild)
            {
                return(Ok(ReturnHelpMethod.ReturnError(IsValidStr.ErrorMembers)));
            }

            return(Ok(managerdBLL.ManagerLogin(Model)));
        }
Esempio n. 6
0
        private async Task <ApplicationUser> HandleRefreshToken(LoginModelRequest loginModel, ResultResponseObject <TokenResponse> resultResponseModel)
        {
            bool credenciaisValidas = false;

            if (String.IsNullOrEmpty(loginModel.RefreshToken))
            {
                RefreshTokenData refreshTokenBase = null;

                string strTokenArmazenado = _cache.GetString(loginModel.RefreshToken);
                if (!String.IsNullOrWhiteSpace(strTokenArmazenado))
                {
                    refreshTokenBase = JsonConvert
                                       .DeserializeObject <RefreshTokenData>(strTokenArmazenado);
                }

                credenciaisValidas = (refreshTokenBase != null &&
                                      loginModel.RefreshToken == refreshTokenBase.RefreshToken);

                // Elimina o token de refresh já que um novo será gerado
                if (credenciaisValidas)
                {
                    _cache.Remove(loginModel.RefreshToken);
                }
            }

            JwtSecurityToken token = null;

            if (!string.IsNullOrWhiteSpace(loginModel.RefreshToken))
            {
                token = new JwtSecurityTokenHandler().ReadJwtToken(loginModel.RefreshToken);
            }

            if (token == null)
            {
                resultResponseModel.AddError("Refresh Token", "Não foi possível ler o refresh token");
            }
            else if (token.ValidTo < DateTime.Now)
            {
                resultResponseModel.AddError("Refresh Token", "Refresh token inválido");
            }
            else
            {
                string userId = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.UniqueName).Value;

                ApplicationUser user = await _userManager.FindByIdAsync(userId);

                return(user);
            }

            return(null);
        }
        public async Task <Result <LoginModelResponse, Error> > Login(LoginModelRequest loginModelRequest)
        {
            var user = await _userRepository.GetByEmail(loginModelRequest.Email);

            if (user == null)
            {
                return(Result.Failure <LoginModelResponse, Error>(ErrorsList.UserNotFound));
            }

            if (!_passwordHasher.Check(user.PasswordHash, loginModelRequest.Password))
            {
                return(Result.Failure <LoginModelResponse, Error>(ErrorsList.InvalidPassword));
            }

            return(Result.Success <LoginModelResponse, Error>(await GenerateToken(user)));
        }
        public LoginResult Login(LoginModelRequest objLoginModelRequest)
        {
            try
            {
                objLoginModelRequest.Password = CryptorEngine.Encrypt(objLoginModelRequest.Password, true);

                LoginResult objUserProfile = _objFriendFitDBEntity.Database.SqlQuery <LoginResult>("LoginCustomer @Email=@Email,@Password=@Password",
                                                                                                   new SqlParameter("Email", objLoginModelRequest.Email),
                                                                                                   new SqlParameter("Password", objLoginModelRequest.Password)).FirstOrDefault();

                return(objUserProfile);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Esempio n. 9
0
        public HttpResponseMessage Login(LoginModelRequest request)
        {
            var accessKey = Global.GetAccessKeyFromHeader(Request);

            if (Global.CheckAccessKey(accessKey))
            {
                var db = Global.DB;

                try
                {
                    var result         = new AccountController();
                    var getUser        = db.Users.FirstOrDefault(item => item.UserName == request.Username);
                    var passwordHasher = new PasswordHasher();
                    if (passwordHasher.VerifyHashedPassword(getUser.PasswordHash, request.Password) == PasswordVerificationResult.Success)
                    {
                        var um   = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));
                        var role = um.GetRoles(getUser.Id).FirstOrDefault();
                        var User = Mapper.Map <ApplicationUser, MobileUserViewModel>(getUser);
                        User.Role = role;

                        if (role == "Groomer" || role == "Customer" || role == "Owner")
                        {
                            return(Request.CreateResponse(HttpStatusCode.OK, new { User }, MediaTypeHeaderValue.Parse("application/json")));
                        }
                        else
                        {
                            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Global.Message_WrongPassword));
                        }
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Global.Message_WrongPassword));
                    }
                }
                catch (Exception ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Global.Message_ErrorMessage));
                }
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Global.Message_WrongAccessKey));
            }
        }
Esempio n. 10
0
        public IHttpActionResult UserLogin([FromBody] LoginModelRequest loginRequest)
        {
            LoginModelResponse loginResponse = new LoginModelResponse();

            try
            {
                if (!ModelState.IsValid)
                {
                    loginResponse.Error = new Error {
                        Code = ErrorCodes.ModelStateInvalid, Message = "Please correct the errors"
                    };
                    return(Ok(loginResponse));
                }
                loginResponse = CustomerLogin.Login(loginRequest);
                return(Ok(loginResponse));
            }
            catch (Exception ex)
            {
                return(Ok(ex.Message));
            }
        }
Esempio n. 11
0
        public ActionResult Signin(LoginModelRequest login)
        {
            LoginModelResponse loginModelResponse = new LoginModelResponse();

            ViewBag.LoginSuccess = "False";

            if (!ModelState.IsValid)
            {
                return(View("Index"));
            }
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings["WebApiBaseUrl"]);

                //HTTP POST
                var responseMessageTask = client.PostAsJsonAsync <LoginModelRequest>("api/Login", login);
                responseMessageTask.Wait();

                var responseMessage = responseMessageTask.Result;
                if (responseMessage.IsSuccessStatusCode)
                {
                    var responseContentTask = responseMessage.Content.ReadAsAsync <LoginModelResponse>();
                    responseContentTask.Wait();
                    loginModelResponse = responseContentTask.Result;
                    if (loginModelResponse.Error == null)
                    {
                        Session["Customer"] = loginModelResponse;
                        return(RedirectToActionPermanent("ProductTypes", "Product"));
                    }
                    ModelState.AddModelError("", loginModelResponse.Error.Message);
                    return(View("Index"));
                }
                else
                {
                    ModelState.AddModelError("", "Server error");
                    return(View("Index"));
                }
            }
        }
Esempio n. 12
0
        public async Task <IActionResult> Login([FromBody] LoginModelRequest request)
        {
            var response = new LoginModelResponse();

            response.UrlApi = HttpContext.Request.Path.Value; // Get URL

            if (request == null)
            {
                response.ErrorMessage = "Request is null";
                response.Success      = false;
                return(BadRequest(response));
            }
            if (String.IsNullOrEmpty(request.Username))
            {
                response.ErrorMessage = "@Username is null or empty";
                response.Success      = false;
                return(BadRequest(response));
            }
            if (String.IsNullOrEmpty(request.Password))
            {
                response.ErrorMessage = "@Password is null or empty";
                response.Success      = false;
                return(BadRequest(response));
            }

            var obj = await this.IAuthenticationService.Login(UserMapper.Map(request));

            if (obj == null)
            {
                response.ErrorMessage = "User not found";
                response.Success      = false;
                return(NotFound(response));
            }

            // Response Ok
            response.User    = obj;
            response.Success = true;
            return(Ok(response));
        }
Esempio n. 13
0
        private async Task <ApplicationUser> HandleUserAuthentication(LoginModelRequest loginModel, ResultResponseObject <TokenResponse> resultResponseModel)
        {
            Microsoft.AspNetCore.Identity.SignInResult result = new Microsoft.AspNetCore.Identity.SignInResult();
            ApplicationUser appUser = _userManager.Users.SingleOrDefault(r => r.UserName == loginModel.Login);

            if (appUser != null)
            {
                result = await _signInManager.PasswordSignInAsync(loginModel.Login, loginModel.Password, false, false);

                if (!result.Succeeded)
                {
                    resultResponseModel.AddError("Login", "Usuário ou senha inválida");
                    appUser = null;
                }
            }
            else
            {
                resultResponseModel.AddError("Login", "Usuário não encontrado");
            }

            return(appUser);
        }
Esempio n. 14
0
 public JsonResult _Login(LoginModelRequest entity, string codetext, bool captchaValid)
 {
     if (ModelState.IsValid)
     {
         ItemResult <AdminCredential> result = new ItemResult <AdminCredential>();
         result = service.Login(new Sys_User()
         {
             LoginAccount = entity.LoginAccount, LoginPassword = entity.LoginPassword
         });
         if (!captchaValid && !string.IsNullOrEmpty(codetext))
         {
             result.Message = "验证码错误";
             result.Success = false;
             return(Json(result, JsonRequestBehavior.DenyGet));
         }
         if (result.Success)
         {
             Session["AdminCredential"] = result.Data;
         }
         return(Json(result, JsonRequestBehavior.DenyGet));
     }
     return(Json(new { Message = "登录失败", Success = false }, JsonRequestBehavior.DenyGet));
 }
Esempio n. 15
0
        public static LoginModelResponse Login(LoginModelRequest login)
        {
            auctionEntities = new AuctionSystemEntities();
            loginResponse   = new LoginModelResponse();
            //To retrive customers based on email.
            customer customer = auctionEntities.customers.Where(c => c.customer_email == login.Email).FirstOrDefault();

            //check if customer already exist or not
            if (customer == null)
            {
                //if customer do not exist set fault as invalid email
                loginResponse.Error = new Error {
                    Code = ErrorCodes.InvalidEmail, Message = "User Email does not exist"
                };
                loginResponse.LoginIsValid = false;
                return(loginResponse);
            }
            //if customer exists check if passwords match by hashing the password
            if (customer.customer_password != CustomerRegistration.HashPassword(login.Password))
            {
                //if paswords do not match set fault as invalid password
                loginResponse.Error = new Error {
                    Code = ErrorCodes.InvalidPassword, Message = "User Email / Password does not match"
                };
                loginResponse.LoginIsValid = false;
                return(loginResponse);
            }

            //if passwords match login the user by setting loginresponse
            loginResponse.Email             = customer.customer_email;
            loginResponse.CustomerId        = customer.id;
            loginResponse.CustomerLastName  = customer.customer_lastname;
            loginResponse.CustomerFirstName = customer.customer_firstname;
            loginResponse.LoginIsValid      = true;

            return(loginResponse);
        }
Esempio n. 16
0
 public static LoginModelRequest WithPassword(this LoginModelRequest loginModel, string password)
 {
     loginModel.Password = password;
     return(loginModel);
 }
Esempio n. 17
0
        private async Task SetAuthenticationToken()
        {
            UserType userType = UserTypeFactory.Default();
            UserType admin    = UserTypeFactory.Default().WithName("Admin");

            City city = CityFactory.Default();

            await ExecuteDatabaseAction(async (doFestContext) =>
            {
                await doFestContext.UserTypes.AddAsync(userType);
                await doFestContext.UserTypes.AddAsync(admin);
                await doFestContext.Cities.AddAsync(city);
                await doFestContext.SaveChangesAsync();
                CityId = city.Id;
            });

            var userRegisterModel = new RegisterModel
            {
                Username       = "******",
                Age            = 20,
                BucketListName = "test bucketlist",
                City           = city.Id,
                Email          = "*****@*****.**",
                Name           = "testtest",
                Password       = "******",
                Year           = 3
            };

            var userRegisterResponse = await HttpClient.PostAsJsonAsync($"api/v1/auth/register", userRegisterModel);

            userRegisterResponse.IsSuccessStatusCode.Should().BeTrue();
            if (_isAdmin == true)
            {
                var userRespository    = new UserRepository(dbContext);
                var userTypeRepository = new UserTypeRepository(userTypeDbContext);
                var userTypeAdmin      = await userTypeRepository.GetByName("Admin");

                var user = await userRespository.GetByEmail(userRegisterModel.Email);

                user.UserTypeId = userTypeAdmin.Id;
                userRespository.Update(user);
                await userRespository.SaveChanges();
            }
            var authenticateModel = new LoginModelRequest
            {
                Email    = userRegisterModel.Email,
                Password = userRegisterModel.Password
            };
            var userAuthenticateResponse = await HttpClient.PostAsJsonAsync($"api/v1/auth/login", authenticateModel);

            userAuthenticateResponse.IsSuccessStatusCode.Should().BeTrue();
            AuthenticatedUserId = new Guid();
            var authenticationResponseContent = await userAuthenticateResponse.Content.ReadAsAsync <LoginModelResponse>();

            var stream  = authenticationResponseContent.Token;
            var handler = new JwtSecurityTokenHandler();
            var tokenS  = handler.ReadToken(stream) as JwtSecurityToken;

            AuthenticatedUserId = new Guid(tokenS.Claims.First(x => x.Type == "userId").Value);

            AuthenticationToken = authenticationResponseContent.Token;
        }
        public HttpResponseMessage Login(LoginModelRequest objLoginModelRequest)
        {
            LoginModelResponse result = new LoginModelResponse();

            if (ModelState.IsValid)
            {
                try
                {
                    Int64 UserId       = _objFriendFitDBEntity.Database.SqlQuery <Int64>("Select Id from UserProfile where Email={0}", objLoginModelRequest.Email).FirstOrDefault();
                    bool  mailVerified = _objFriendFitDBEntity.Database.SqlQuery <bool>("select EmailConfirmed from UserProfile where Id={0}", UserId).FirstOrDefault();
                    if (mailVerified == false)
                    {
                        result.Response.StatusCode = Convert.ToInt32(HttpStatusCode.NotAcceptable);
                        result.Response.Message    = "Please Verify Your Email Id that has been sent to your mail.";
                    }
                    else
                    {
                        result.Response = _objIUserSettings.Login(objLoginModelRequest);
                        //Int64 UserId = _objFriendFitDBEntity.Database.SqlQuery<Int64>("select Id from UserProfile where Email={0}", objLoginModelRequest.Email).FirstOrDefault();

                        if (result.Response != null)
                        {
                            string Token = _objFriendFitDBEntity.Database.SqlQuery <string>("select TokenCode from UserToken where UserId={0}", UserId).FirstOrDefault();

                            if (Token == null || Token == "0")
                            {
                                if (Token == null)
                                {
                                    UserToken objToken = new UserToken()
                                    {
                                        UserId     = result.Response.Id,
                                        RoleId     = result.Response.RoleId,
                                        CreatedOn  = DateTime.Now,
                                        IsActive   = true,
                                        ExpiryDate = DateTime.Now.AddDays(7),
                                        TokenCode  = Guid.NewGuid().ToString() + result.Response.Id.ToString() + Guid.NewGuid().ToString()
                                    };
                                    _objFriendFitDBEntity.UserTokens.Add(objToken);
                                    _objFriendFitDBEntity.SaveChanges();
                                    result.Response.TokenCode = objToken.TokenCode;
                                }
                                else
                                {
                                    int rowEffected = _objFriendFitDBEntity.Database.ExecuteSqlCommand("Update Token set TokenCode=@TokenCode,ExpiryDate=@ExpiryDate where UserId=@UserId",
                                                                                                       new SqlParameter("TokenCode", Guid.NewGuid().ToString() + result.Response.Id.ToString() + Guid.NewGuid().ToString()),
                                                                                                       new SqlParameter("ExpiryDate", DateTime.Now.AddDays(7)),
                                                                                                       new SqlParameter("UserId", UserId));
                                }
                            }
                            else
                            {
                                result.Response.TokenCode = Token;
                            }
                            result.Response.StatusCode = Convert.ToInt32(HttpStatusCode.OK);
                            result.Response.Message    = "You are logged in successfully!";
                        }
                        else
                        {
                            var GetIsActive = _objFriendFitDBEntity.UserProfiles.Where(a => a.Password == objLoginModelRequest.Password && a.Email == objLoginModelRequest.Email).FirstOrDefault();
                            if (GetIsActive != null)
                            {
                                var IsActive = _objFriendFitDBEntity.UserProfiles.Where(a => a.Password == objLoginModelRequest.Password && a.Email == objLoginModelRequest.Email && a.IsActive == true && a.IsDeleted == false).FirstOrDefault();
                                if (IsActive != null)
                                {
                                    FResponse res = new FResponse();
                                    res.StatusCode = Convert.ToInt32(HttpStatusCode.Unauthorized);
                                    res.Message    = "Email or Password is Incorrect";
                                    _response      = Request.CreateResponse(HttpStatusCode.Unauthorized, res);
                                }
                                else
                                {
                                    FResponse res = new FResponse();
                                    res.StatusCode = Convert.ToInt32(HttpStatusCode.Unauthorized);
                                    res.Message    = "Your Account is currently disabled kindly contact Admin.";
                                    _response      = Request.CreateResponse(HttpStatusCode.Unauthorized, res);
                                }
                            }
                            else
                            {
                                FResponse res = new FResponse();
                                res.StatusCode = Convert.ToInt32(HttpStatusCode.Unauthorized);
                                res.Message    = "Email or Password is Incorrect";
                                _response      = Request.CreateResponse(HttpStatusCode.Unauthorized, res);
                            }

                            return(_response);
                        }
                    }
                }
                catch (Exception ex)
                {
                    result.Response.StatusCode = Convert.ToInt32(HttpStatusCode.BadRequest);
                    _response = Request.CreateResponse(HttpStatusCode.InternalServerError, "Some error occurred");
                }
            }
            else
            {
                result.Response.StatusCode = Convert.ToInt32(HttpStatusCode.BadRequest);
                _response = Request.CreateResponse(HttpStatusCode.InternalServerError, "Model is not valid");
            }
            //result.Response.StatusCode = Convert.ToInt32(HttpStatusCode.OK);
            //result.Response.Message = "Success";
            _response = Request.CreateResponse(HttpStatusCode.OK, result);
            return(_response);
        }
Esempio n. 19
0
 public static LoginModelRequest WithEmail(this LoginModelRequest loginModel, string email)
 {
     loginModel.Email = email;
     return(loginModel);
 }
Esempio n. 20
0
        /// <summary>
        /// 管理员登录操作
        /// </summary>
        /// <param name="Model"></param>
        /// <param name="GetLoginIp"></param>
        /// <returns></returns>
        public ResultMsg ManagerLogin(LoginModelRequest Model, string GetLoginIp = "127.0.0.1")
        {
            Sys_Manager managerModel = baseDAL.GetModelAll<Sys_Manager>("Name=@Name", new { Name = Model.UserName });

            //检查用户是否存在
            if (managerModel == null)
            {
                return ReturnHelpMethod.ReturnWarning((int)HttpCodeEnum.Http_1002);
            }

            //检查密码
            string PassWord = DESEncryptMethod.Encrypt(Model.PassWord, managerModel.RandomCode);
            if (PassWord != managerModel.Password)
            {
                return ReturnHelpMethod.ReturnWarning((int)HttpCodeEnum.Http_1002);
            }

            //查询用户角色
            Sys_ManagerRole managerroleModel = baseDAL.GetModelById<Sys_ManagerRole>(managerModel.RelationId);

            //返回管理员信息
            ManagerReturnModel adminModel = new ManagerReturnModel()
            {
                UserId = managerModel.Id,
                AdminName = String.IsNullOrEmpty(managerModel.Nickname) ? managerModel.Name : managerModel.Nickname,
                Avatar = managerModel.Avatar,
                RoleName = managerroleModel.RoleName,
                RegisteTime = managerroleModel.AddTime.Value,
            };

            //登录成功报存管理员信息
            string Token = DESEncryptMethod.Encrypt(managerModel.Id.ToString(), ExpandMethod.GetTimeStamp());

            //处理单点登录问题
            //if (!String.IsNullOrEmpty(managerModel.TokenId))
            //{
            //    redis.KeyDelete(managerModel.TokenId);
            //}

            managerModel.TokenId = Token;
            managerModel.LoginTimes = managerModel.LoginTimes + 1;
            managerModel.LastLoginIP = GetLoginIp;
            managerModel.LastLoginTime = DateTime.Now;

            RedisManagerModel redisManagerModel = new RedisManagerModel()
            {
                Id = managerModel.Id,
                RelationId = managerModel.RelationId,
                Name = managerModel.Name,
                Avatar = managerModel.Avatar,
                Nickname = managerModel.Nickname,
                Phone = managerModel.Phone,
                Email = managerModel.Email,
                LoginTimes = managerModel.LoginTimes,
                LastLoginIP = managerModel.LastLoginIP,
                LastLoginTime = managerModel.LastLoginTime,
                IsDefault = managerModel.IsDefault,
                Remarks = managerModel.Remarks,
            };

            redis.StringSet(Token, redisManagerModel, TimeSpan.FromMinutes(30));

            baseDAL.UpdateModel<Sys_Manager>(managerModel);

            return ReturnHelpMethod.ReturnSuccess((int)HttpCodeEnum.Http_1001, new { Data = adminModel, Token = Token });
        }