public async Task <ResponseEntity <LoginResponseDTO> > LoginRequest(string username, string password)
        {
            LoginRequestDTO request = new LoginRequestDTO
            {
                UserName = username,
                Password = password
            };

            using (var httpClient = new System.Net.Http.HttpClient())
            {
                StringContent content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");

                ResponseEntity <LoginResponseDTO> responseDto;

                using (var response = await httpClient.PostAsync("https://e-out-test.stockmount.com/api/user/dologin", content))
                {
                    response.EnsureSuccessStatusCode();
                    string responseStr = await response.Content.ReadAsStringAsync();

                    try
                    {
                        responseDto = JsonConvert.DeserializeObject <ResponseEntity <LoginResponseDTO> >(responseStr);
                        return(responseDto);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
Example #2
0
 public IActionResult RefreshToken(LoginRequestDTO request, string refreshToken)
 {
     if (_service.CheckRefreshToken(refreshToken, request.Login))
     {
         var claims = new[]
         {
             new Claim(ClaimTypes.NameIdentifier, request.Login)
         };
         var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
         var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
         var token = new JwtSecurityToken
                     (
             issuer: "School",
             audience: "Students",
             claims: claims,
             expires: DateTime.Now.AddMinutes(10),
             signingCredentials: creds
                     );
         return(Ok(new
         {
             token = new JwtSecurityTokenHandler().WriteToken(token)
         }));
     }
     return(StatusCode(401));
 }
Example #3
0
        public async Task <bool> LogInAsync(LoginRequestDTO loginRequest, IOutputPort <LoginResponseDTO> outputPort)
        {
            try
            {
                _logger.LogInformation("Logging user for request {@request}", loginRequest);

                if (loginRequest.Username.IsValidString() && loginRequest.Password.IsValidString())
                {
                    var user = await _userRepository.FindByNameAsync(loginRequest.Username);

                    if (user != null)
                    {
                        if (await _userRepository.CheckPasswordAsync(user, loginRequest.Password))
                        {
                            var token = await _jwtFactory.GenerateTokenAsync(user.Id, user.UserName);

                            _logger.LogInformation("Login succesfull, token generated succesful");

                            outputPort.CreateResponse(new LoginResponseDTO(token, true));
                            return(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.Message);
                outputPort.CreateResponse(new LoginResponseDTO(false, new ErrorResponse(new[] { GlobalErrors.UnexpectedError })));
                return(false);
            }

            outputPort.CreateResponse(new LoginResponseDTO(false, new ErrorResponse(new[] { new Error(GlobalErrorCodes.InvalidCredentials, "Username or password is invalid") })));
            return(false);
        }
Example #4
0
        public IActionResult Login(LoginRequestDTO request)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, "1"),
                new Claim(ClaimTypes.Name, "John"),
                new Claim(ClaimTypes.Role, "admin"),
                new Claim(ClaimTypes.Role, "everyone")
            };

            var key = new SymmetricSecurityKey
                          (Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken
                        (
                issuer: "Asus",
                audience: "everyone",
                claims: claims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: creds

                        );

            return(Ok(new
            {
                accessToken = new JwtSecurityTokenHandler().WriteToken(token),
                refreshToken = Guid.NewGuid()
            }
                      ));;
        }
        /// <summary>
        /// 获取 Token
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool IsAuthenticated(LoginRequestDTO request, out string token)
        {
            token = string.Empty;
            if (request.Username != "admin" || request.Password != "123456")
            {
                return(false);
            }
            request.UserId = 1;

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, request.Username),
                new Claim(ClaimTypes.NameIdentifier, request.UserId.ToString())
            };

            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken    = new JwtSecurityToken(
                _tokenManagement.Issuer,
                _tokenManagement.Audience, claims,
                expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration),
                signingCredentials: credentials
                );

            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            RedisHelper.Set(RedisPrefix.User_Login_Token_Key.GetKey(request.UserId), token, _tokenManagement.AccessExpiration * 60);
            return(true);
        }
Example #6
0
        public IActionResult Login(LoginRequestDTO loginRequest)
        {
            if (!Student.IsItPossibleToLogIn(loginRequest))
            {
                return(StatusCode(403));
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, loginRequest.Login),
                new Claim(ClaimTypes.Role, Student.GetRole(loginRequest.Login))
            };
            var key            = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecretKey"]));
            var myRefreshToken = Guid.NewGuid();
            var token          = new JwtSecurityToken
                                 (
                issuer: "Valera",
                audience: "Students",
                claims: claims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                                 );

            Student.UpdateRefreshToken(loginRequest.Login, myRefreshToken);
            return(Ok(new {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                refreshToken = myRefreshToken
            }));
        }
Example #7
0
        public bool CheckCredentials(LoginRequestDTO request)
        {
            using (var client = new SqlConnection("Data Source=db-mssql;Initial Catalog=s18734;Integrated Security=True"))
                using (var com = new SqlCommand())
                {
                    client.Open();
                    com.Connection  = client;
                    com.CommandText = "select salt from student where indexnumber = @id2";
                    com.Parameters.AddWithValue("id2", request.Login);
                    var    dr        = com.ExecuteReader();
                    string haslosalt = "";
                    dr.Read();
                    haslosalt = dr["Salt"].ToString();
                    dr.Close();


                    var hash = CreateHash(request.Haslo, haslosalt);

                    com.CommandText = "select password from Student where indexnumber=@id2";

                    dr = com.ExecuteReader();
                    dr.Read();
                    string haslo = (string)dr.GetValue(0);
                    dr.Close();

                    if (!haslo.Equals(hash))
                    {
                        return(false);
                    }
                    return(true);
                }
        }
Example #8
0
        public bool IsAuthenticated(LoginRequestDTO request, out string token)
        {
            token = string.Empty;
            if (!user.IsValid(request))
            {
                return(false);
            }
            // 查看控制器WeatherForecastController如何获取已认证的用户信息
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, request.Username),
                new Claim(ClaimTypes.Role, "superadmin"),
                new Claim(ClaimTypes.GivenName, "我的天啦")
            };
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken    = new JwtSecurityToken(
                tokenManagement.Issuer,
                tokenManagement.Audience,
                claims,
                expires: DateTime.Now.AddMinutes(tokenManagement.AccessExpiration),
                signingCredentials: credentials
                );

            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return(true);
        }
        public async Task <IActionResult> RequestToken([FromBody] LoginRequestDTO request)
        {
            var result = await _accountQueryService.ValidateUser(request.Username, request.Password);

            if (result != null)
            {
                var token = await GenerateJwtToken(result);

                return(Ok(new
                {
                    status = "success",
                    result = new
                    {
                        token = token,
                        info = new
                        {
                            name = result.Name,
                            id = result.Id,
                            email = result.Email
                        }
                    }
                }));
            }

            return(BadRequest("Could not verify username and password"));
        }
        public async void Login_ValidCredentials_Ok()
        {
            // Arrange
            var client   = _server.Instance.CreateClient();
            var loginReq = new LoginRequestDTO
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var content = new StringContent(JsonConvert.SerializeObject(loginReq), Encoding.UTF8, "application/json");

            // Act
            var response = await client.PostAsync("api/auth/login", content);

            // Assert
            var stream = await response.Content.ReadAsStreamAsync();

            TokenResponseDTO data = null;

            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                data = JsonConvert.DeserializeObject <TokenResponseDTO>(await reader.ReadToEndAsync());
            }

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotNull(data.AccessToken);
            Assert.NotNull(data.RefreshToken);
        }
Example #11
0
        public bool IsAuthenticated(LoginRequestDTO request, out string token, out string userid)
        {
            token  = string.Empty;
            userid = string.Empty;

            if (!_userService.IsValid(request))
            {
                return(false);
            }

            //用户Id
            userid = _userService.GetUserId(request.Username).ToString();

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, request.Username)
            };
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken    = new JwtSecurityToken(_tokenManagement.Issuer, _tokenManagement.Audience, claims, expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration), signingCredentials: credentials);

            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            return(true);
        }
Example #12
0
 public async Task <IActionResult> PortalLogin([FromBody] LoginRequestDTO model)
 {
     return(Ok(await _databaseTutorUOW.UserRepository.ProcessLogin(new RequestDTO <LoginRequestDTO>()
     {
         Data = model
     })));
 }
Example #13
0
        public User LogIn(string username, string password)
        {
            LoginRequestDTO loginRequestDTO = new LoginRequestDTO(username, password);

            try
            {
                LoginResponseDTO loginResponseDTO = new LoginResponseDTO(MojUserPortClient.login(loginRequestDTO.LoginRequest));
                User             response         = loginResponseDTO.User;

                User userDB = unitOfWork.Users.SingleOrDefault(u => u.Id == response.Id);

                if (userDB != null)
                {
                    userDB = response;
                    unitOfWork.Complete();
                }
                else
                {
                    unitOfWork.Users.Add(response);
                    unitOfWork.Complete();
                }

                return(response);
            }
            catch
            {
                return(null);
            }
        }
        public IActionResult Login([FromBody] LoginRequestDTO request)
        {
            Guid guid = Guid.NewGuid();

            _log.RegistrarEvento($"{guid.ToString()}{Environment.NewLine}{Newtonsoft.Json.JsonConvert.SerializeObject(request)}");

            LoginResponseDTO response = new LoginResponseDTO();

            try
            {
                response.Result.Data = _usersService.AuthenticateUsers(request.UserName, EncryptionLibrary.EncryptText(request.Password));

                response.Result.Success = true;
            }
            catch (ResultException ex)
            {
                response.Result = new Result()
                {
                    Success = true, ErrCode = ex.Result.ErrCode, Message = ex.Result.Message
                };
            }
            catch (Exception ex)
            {
                response.Result = new Result()
                {
                    Success = false, Message = "Ocurrio un problema en el servicio, intentelo nuevamente."
                };
                _log.RegistrarEvento(ex, guid.ToString());
            }

            _log.RegistrarEvento($"{guid.ToString()}{Environment.NewLine}{Newtonsoft.Json.JsonConvert.SerializeObject(response)}");

            return(Ok(response));
        }
Example #15
0
        public LoginResponseDTO GetRole(LoginRequestDTO request)
        {
            using (var con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s14354;Integrated Security=True"))
                using (var com = new SqlCommand())
                {
                    com.Connection = con;
                    //hash
                    request.Haslo = Hash(request.Haslo, GetSalt(request.Login));

                    com.CommandText = "select IndexNumber, LastName, Role from Student where IndexNumber = @index and Password = @password";
                    com.Parameters.AddWithValue("index", request.Login);
                    com.Parameters.AddWithValue("password", request.Haslo);
                    con.Open();
                    var dr = com.ExecuteReader();
                    while (dr.Read())
                    {
                        var response = new LoginResponseDTO();
                        response.id   = dr["IndexNumber"].ToString();
                        response.name = dr["LastName"].ToString();
                        response.role = dr["Role"].ToString();
                        return(response);
                    }
                    return(null);
                }
        }
Example #16
0
        public ActionResult Login([FromBody] LoginRequestDTO request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid Request"));
            }

            //下面签发JwtToken

            //用户名密码校验成功

            var claims = new[]
            {
                new Claim("SubId", "10001"),
                new Claim("LoginName", request.UserName)
            };
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtTokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken    = new JwtSecurityToken(_jwtTokenManagement.Issuer,
                                                   _jwtTokenManagement.Audience,
                                                   claims,
                                                   expires: DateTime.Now.AddMinutes(_jwtTokenManagement.AccessExpiration),
                                                   signingCredentials: credentials);

            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            return(Ok(token));
        }
Example #17
0
        public async Task <User> Authenticate(LoginRequestDTO loginRequest)
        {
            var user = await _context.User.FirstOrDefaultAsync(u => u.Email == loginRequest.Username);

            if (user == null)
            {
                throw new HttpResponseException("User does not exist! Create account before login");
            }


            var passwordHasher = new PasswordHasher(new HashingOptions()
            {
            });
            var passwordVerified = passwordHasher.Check(user.Password, loginRequest.Password);

            if (passwordVerified == false)
            {
                throw new HttpResponseException("Password is wrong. Please fill the correct password!");
            }
            else
            {
                return(user);
            }

            /*var user = await _context.User.FirstOrDefaultAsync(u => u.Email == loginRequest.Username && u.Password == loginRequest.Password);
             * if(user == null)
             *  return null;*/
        }
Example #18
0
        public IActionResult Login(LoginRequestDTO request)
        {
            var salt     = EnrollmentsController.CreateSalt();
            var password = EnrollmentsController.Create("das8dha8dadha8", salt);

            string login;
            string name;

            using (var con = new SqlConnection(connection))
                using (var com = new SqlCommand())
                {
                    com.Connection  = con;
                    com.CommandText = "SELECT * FROM student WHERE indexnumber = @indexnumber";
                    com.Parameters.AddWithValue("indexnumber", request.Login);


                    con.Open();

                    var dr = com.ExecuteReader();

                    if (!dr.Read())
                    {
                        return(BadRequest("Incorrect login or password"));
                    }
                    if (!Validate(request.Pass, dr["salt"].ToString(), dr["password"].ToString()))
                    {
                        return(Unauthorized("Incorrect login or password"));
                    }
                    login = dr["IndexNumber"].ToString();
                    name  = dr["FirstName"].ToString();
                }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, login),
                new Claim(ClaimTypes.Name, name),
                new Claim(ClaimTypes.Role, "employee"),
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken
                        (
                issuer: "Admin",
                audience: "Employees",
                claims: claims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: creds
                        );

            var refreshtoken = Guid.NewGuid();

            setRefreshToken(refreshtoken.ToString(), login);
            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                refreshtoken
            }));
        }
Example #19
0
        public bool CheckPassword(LoginRequestDTO request)
        {
            using (var con = new SqlConnection(builder.ConnectionString))
                using (var com = new SqlCommand())
                {
                    com.Connection = con;
                    con.Open();

                    // Sprawdzanie haseł sprzed ich zabezpieczenia
                    //   com.CommandText = "SELECT 1 FROM Student WHERE IndexNumber=@number AND Password=@Password";
                    //   com.Parameters.AddWithValue("number", request.Login);
                    //  com.Parameters.AddWithValue("Password", request.Password);

                    //    var dr = com.ExecuteReader();

                    //   return dr.Read();

                    com.CommandText = "SELECT Password,Salt FROM Student WHERE IndexNumber=@number";
                    com.Parameters.AddWithValue("number", request.Login);

                    using var dr = com.ExecuteReader();

                    if (dr.Read())
                    {
                        return(SecurePassword.Validate(request.Password, dr["Salt"].ToString(), dr["Password"].ToString()));
                    }
                    return(false); //Nie ma nawet takiego indeksu w bazie danych
                }
        }
Example #20
0
        public async Task <LoginResponseDTO> LoginAsync(LoginRequestDTO request)
        {
            User user = await usersRepository.FindByEmailAsync(request.Email);

            if (user == null)
            {
                throw new BadRequestException("User does not exist!");
            }

            bool passwordIsCorrect = await usersRepository.CheckPasswordAsync(user, request.Password);

            if (!passwordIsCorrect)
            {
                throw new ForbiddenException("Password is incorrect!");
            }
            Claim[] userClaims = await GetAuthTokenClaimsForUserAsync(user);

            var accessToken  = tokenGenerator.GenerateTokenForClaims(userClaims);
            var refreshToken = refreshTokenFactory.GenerateRefreshToken();
            await usersRepository.CreateRefreshTokenAsync(user, refreshToken);

            return(new LoginResponseDTO
            {
                Email = user.Email,
                Token = accessToken,
                RefreshToken = refreshToken
            });
        }
        public bool IsAuthenticated(LoginRequestDTO request, out string token)
        {
            token = string.Empty;
            if (!_userService.IsValid(request))
            {
                return(false);
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, request.Username),
            };
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken    = new JwtSecurityToken(
                issuer: _tokenManagement.Issuer,
                audience: _tokenManagement.Audience,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddSeconds(_tokenManagement.AccessExpiration),
                claims: claims,
                signingCredentials: credentials);

            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            return(true);
        }
Example #22
0
        public ResponseResult <LoginResponseDTO> LoginByAccount(LoginRequestDTO request)
        {
            Log.Info($"deviceId={request.Client.DeviceId}&clientver={request.Client.Version}&source={request.Client.Type}&userCode={request.UserCode}&password={request.Password}");
            var app = OAuthAppCache.Get(request.Appid);

            if (app == null)
            {
                return(Fail <LoginResponseDTO>("无效的应用id", "0400"));
            }

            LoginProvider loginProvider = new LoginProvider(request.UserCode, request.Password, request.Scopes, (LoginType)request.LoginType);

            if (!loginProvider.Login(request.Client.Type, request.Client.System, request.Client.DeviceId, request.Client.IP, request.Client.SessionId, request.Client.Version, app.Id))
            {
                return(Fail <LoginResponseDTO>(loginProvider.PromptInfo.CustomMessage));
            }
            LoginResponseDTO response = new LoginResponseDTO()
            {
                Token          = loginProvider.Token,
                Expires        = loginProvider.OAuthUser.Expire_In,
                Openid         = loginProvider.OAuthUser.Open_Id,
                RefreshExpires = loginProvider.OAuthUser.Refresh_Expire_In,
                RefreshToken   = loginProvider.OAuthUser.Refresh_Token,
            };

            return(Success(response));
        }
Example #23
0
        public async Task <IActionResult> Login([FromBody] LoginRequestDTO model)
        {
            Logger.LogError("Login method called");

            if (!ModelState.IsValid)
            {
                return(BadRequest(new ModelStateErrorResponseDTO(HttpStatusCode.BadRequest, ModelState)));
            }

            ApplicationUser user = null;

            try
            {
                // TODO verify user from API
                user = UserRepository.Get(x => x.BVN == model.BVN)
                       .FirstOrDefault();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error while logging user in");
                return(BadRequest(new ErrorResponseDTO(HttpStatusCode.BadRequest,
                                                       new string[] { "Could not complete request. Please retry later, or contact the support team" })));
            }

            if (user == null || user.ShouldDelete)
            {
                return(BadRequest(new ErrorResponseDTO(HttpStatusCode.BadRequest,
                                                       new List <string> {
                    "You do not have an account with us kindly proceed to signup."
                })));
            }

            return(Ok(GetJWTToken(user)));
        }
Example #24
0
        public LoginResponseDTO Login(LoginRequestDTO dto)
        {
            LoginResponseDTO res;

            if (dto == null)
            {
                res = new LoginResponseDTO()
                {
                    Success  = false,
                    ErrorMsg = "传入对象为空"
                }
            }
            ;
            else
            {
                try
                {
                    res = _login(dto);
                }
                catch (Exception ex)
                {
                    res = new LoginResponseDTO()
                    {
                        Success  = false,
                        ErrorMsg = ex.Message
                    };
                }
            }
            Log.Info($"Login", dto, res);
            return(res);
        }
Example #25
0
        public IActionResult Login(LoginRequestDTO request)
        {
            if (!_service.AuthorizeStudent(request.Login, request.Password))
            {
                return(StatusCode(403));
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, request.Login),
                new Claim(ClaimTypes.Role, "employee")
            };
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken
                        (
                issuer: "School",
                audience: "Students",
                claims: claims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: creds
                        );

            var RefreshToken = Guid.NewGuid();

            _service.SetRefreshToken(RefreshToken.ToString(), request.Login);

            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                refreshToken = RefreshToken
            }));
        }
Example #26
0
        public LoginPageViewModel(INavigationService navigationService, IPageDialogService dialogService,
                                  LoginManager loginManager, SystemStatusManager systemStatusManager,
                                  AppStatus appStatus, RecordCacheHelper recordCacheHelper)
        {
            this.navigationService   = navigationService;
            this.dialogService       = dialogService;
            this.loginManager        = loginManager;
            this.systemStatusManager = systemStatusManager;
            this.appStatus           = appStatus;
            this.recordCacheHelper   = recordCacheHelper;
            LoginCommand             = new DelegateCommand(async() =>
            {
                using (IProgressDialog fooIProgressDialog = UserDialogs.Instance.Loading($"請稍後,更新資料中...", null, null, true, MaskType.Black))
                {
                    LoginRequestDTO loginRequestDTO = new LoginRequestDTO()
                    {
                        Account  = Account,
                        Password = Password,
                    };
                    var fooResult = await LoginUpdateTokenHelper.UserLoginAsync(dialogService, loginManager, systemStatusManager,
                                                                                loginRequestDTO, appStatus);
                    if (fooResult == false)
                    {
                        return;
                    }
                    await recordCacheHelper.RefreshAsync(fooIProgressDialog);
                }

                //await dialogService.DisplayAlertAsync("Info", "登入成功", "OK");
                await navigationService.NavigateAsync("/MDPage/NaviPage/HomePage");
            });
        }
Example #27
0
        public void ProcessRequest(HttpContext context)
        {
            LoginResponseDTO res;
            LoginRequestDTO  dto = new LoginRequestDTO()
            {
                PlatformId   = HttpExtension.GetRequestParam("PlatformId"),
                UserCode     = HttpExtension.GetRequestParam("UserCode"),
                UserPassword = HttpExtension.GetRequestParam("UserPassword")
            };

            if (dto.PlatformId.IsEmpty() || dto.UserCode.IsEmpty() || dto.UserPassword.IsEmpty())
            {
                res = new LoginResponseDTO()
                {
                    Success  = false,
                    ErrorMsg = "登陆信息不完整"
                };
            }
            else
            {
                res = new CommonController().Login(dto);
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(res.ToJson());
        }
Example #28
0
        //登录用户名,密码验证
        public bool IsValid(LoginRequestDTO req)
        {
            //var logger = NLog.LogManager.GetLogger("rlf");

            if (req == null || string.IsNullOrEmpty(req.Username) || string.IsNullOrEmpty(req.Password))
            {
                return(false);
            }

            //logger.Debug(req.Username);

            IFreeSql fsql = FreeSqlFactory.GetIFreeSql("rlfmain", FreeSql.DataType.Sqlite);

            Users users = fsql.Select <Users>().Where(t => t.UserName == req.Username && t.Password == req.Password).ToOne();

            if (users == null)
            {
                return(false);
            }

            //更新登录时间
            fsql.Update <Users>().Set(x => x.LoginTime, System.DateTime.Now).Where(x => x.Id == users.Id).ExecuteAffrows();

            return(true);
        }
Example #29
0
 public IActionResult Login([FromBodyAttribute] LoginRequestDTO data)
 {
     try
     {
         bool exito;
         var  user = _authService.Authenticate(data, out exito);
         if (exito)
         {
             var secretKey = _configuration.GetValue <string>("SecretKey");
             var token     = _authService.GenerateToken(user, secretKey);
             return(Ok(new LoginResponseDTO()
             {
                 data = new { user.Cedula, user.Nombres, user.Id, token }
             }));
         }
         else
         {
             return(Ok(new ResponseDTO()
             {
                 type = "E",
                 message = "Datos Incorrectos"
             }));
         }
     }
     catch (Exception ex)
     {
         return(Ok(new ResponseDTO()
         {
             type = "E",
             message = ex.Message
         }));
     }
 }
Example #30
0
        // 使用者帳號與密碼可以使用 user1~user50 / password1~password50
        public async Task LoginAsync(string account, string password)
        {
            string          url             = "https://lobworkshop.azurewebsites.net/api/Login";
            LoginRequestDTO loginRequestDTO = new LoginRequestDTO()
            {
                Account  = account,
                Password = password
            };
            var                 httpJsonPayload = JsonConvert.SerializeObject(loginRequestDTO);
            HttpClient          client          = new HttpClient();
            HttpResponseMessage response        = await client.PostAsync(url,
                                                                         new StringContent(httpJsonPayload, System.Text.Encoding.UTF8, "application/json"));

            if (response.IsSuccessStatusCode)
            {
                String strResult = await response.Content.ReadAsStringAsync();

                APIResult apiResult = JsonConvert.DeserializeObject <APIResult>(strResult, new JsonSerializerSettings {
                    MetadataPropertyHandling = MetadataPropertyHandling.Ignore
                });
                if (apiResult.Status == true)
                {
                    string itemJsonContent = apiResult.Payload.ToString();
                    item = JsonConvert.DeserializeObject <LoginResponseDTO>(itemJsonContent, new JsonSerializerSettings {
                        MetadataPropertyHandling = MetadataPropertyHandling.Ignore
                    });

                    string content = JsonConvert.SerializeObject(item);
                    await StorageUtility.WriteToDataFileAsync(Constants.DataFolder, Constants.LoginServiceFilename, content);
                }
            }
        }