public void Login(Action <bool> callback = null) { loginStatus = LoginStatus.LOGINING; Dictionary <string, string> headerDic = new Dictionary <string, string>(); string timeStr = ((int)SystemClock.Now).ToString(); LoginBody body = GetLoginBody(); Header header = Header.GetHeader(headerDic); HttpRequestTool.SendMessage( body, (x) => { Debug.Log("Login Sucess :" + x); JSONNode respons = JSONNode.Parse(x); ParseLoginResponse(respons, callback); }, (x) => { Debug.LogError("Login Fail :" + x); if (callback != null) { callback.Invoke(false); } loginStatus = LoginStatus.LOGINFAIL; }, header, false); }
public Driver Login(LoginBody loginBody) { using (ISession session = NH.OpenSession()) { try { var _password = session.CreateSQLQuery($"select Drv_Password from dbo.Drivers where Drv_Ident={loginBody.ident}").UniqueResult <string>(); Log(_password); var check = loginBody.password == _password;//BCrypt.Net.BCrypt.CheckPassword(loginBody.password, _password); if (check) { return(session.Query <Driver>().FetchMany(x => x.OpinionList) .Where(x => x.Drv_Identity == loginBody.ident).FirstOrDefault()); } else { return(null); } // return result;//result.FirstOrDefault(); } catch (Exception e) { Log(e.Message); return(null); } } }
public async Task <ActionResult> LoginUser([FromBody] LoginBody body) { SignInResult signInResult = await signInManager.PasswordSignInAsync(body.Username, body.Password, body.KeepLoggedIn, false); return(signInResult.Succeeded ? (ActionResult)Ok() : BadRequest()); }
public BundleStartBody(string name, string url = null) : base(name, url) { constUpdate = new Body(URLConfig.ConstUpdate); appUpdate = new VersionInfoBody(URLConfig.AppVersion); appUpdate.assetVersion = AssetBundleManager.Inst.GetVersion(); login = LoginManager.Inst.GetLoginBody(); }
static HttpContent CreateLoginContent(string userId, string password) { var body = new LoginBody(userId, password); var json = JsonConvert.SerializeObject(body); return(new StringContent(json, Encoding.UTF8, RestConstants.JSON_HEADER)); }
public async Task <IActionResult> CreateGameServerIdentityToken([FromBody] LoginBody login) { try { var token = await service.CreateGameServerIdentityToken(login); if (token == null) { return(Error(new ErrorResult { Code = 900, Classification = ErrorClassification.EntityNotFound, Message = "Invalid login information" }, HttpStatusCode.NotFound)); } return(Ok(token)); } catch (Exception) { return(Error(new ErrorResult { Code = 500, Classification = ErrorClassification.InternalError, Message = "Failed creating identity token" })); } }
public async Task <IActionResult> Login( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "login")] [RequestBodyType(typeof(LoginBody), "Credentials")] LoginBody loginBody) { // check if all fields are filled in if (loginBody.Email == null || loginBody.Password == null) { return(new BadRequestObjectResult(new ErrorResponse(ErrorCode.INVALID_REQUEST_BODY))); } // verify login credentials User user = await authService.VerifyLogin(loginBody); // if the login failed if (user == null) { return(new UnauthorizedObjectResult(new ErrorResponse(ErrorCode.INVALID_COMBINATION_OF_EMAIL_AND_PASSWORD))); } // get token Token token = await tokenService.CreateToken(user); // get the created user UserResponse response = await userService.GetUser(user.Id); return(new OkObjectResult(new TokenBody { Token = token.Value, User = response })); }
public async Task Login_ShouldReturnNotFoundResult_WhenCredentialsAreInvalid() { // Arrange LoginBody credentials = new LoginBody { UserNameOrEmail = "myUsername", Password = "******" }; Mock <IMediator> mediatorMock = new Mock <IMediator>(); mediatorMock .Setup(m => m.Send(It.IsAny <LoginCommand>(), It.IsAny <CancellationToken>())) .ReturnsAsync((AuthenticatedUserResource)null); MapperConfiguration mapperConfiguration = new MapperConfiguration(config => { config.CreateMap <LoginBody, LoginCommand>(); }); IMapper mapperMock = mapperConfiguration.CreateMapper(); SessionController controller = new SessionController(mediatorMock.Object, mapperMock); // Act ActionResult <AuthenticatedUserResource> response = await controller.Login(credentials); // Assert UnauthorizedObjectResult result = Assert.IsType <UnauthorizedObjectResult>(response.Result); ErrorResource error = Assert.IsType <ErrorResource>(result.Value); Assert.Equal(StatusCodes.Status401Unauthorized, error.StatusCode); }
public StatusCodeResult postLogin([FromBody] LoginBody body) { Admin admin = _context.Admins.FirstOrDefault(curAdmin => curAdmin.Username == body.Username); if (admin != null && admin.Password == body.Password) { HttpContext.Session.SetString("isAdmin", "yes"); return(StatusCode(200)); } return(StatusCode(404)); }
public async Task <ActionResult <UserViewModel> > Login([FromBody] LoginBody loginBody) { try { var result = await AuthService.Login(loginBody.Email, loginBody.Password, loginBody.Remember); return(Ok(result)); } catch (Exception e) { Logger.LogInformation("Login error {Exception}", e.ToString()); return(Unauthorized(e.Message)); } }
public async Task <LoginResponse> LoginAsync(BaseData baseData, LoginBody loginBody) { // @POST("https://rest-{tier}.immedia-semi.com/api/v4/account/login") // Observable<LoginResponse> login(@Body LoginBody paramLoginBody, @Path("tier") String paramString); // // @POST("https://rest-{tier}.immedia-semi.com/api/v4/account/login") // Call<LoginResponse> loginCall(@Body LoginBody paramLoginBody, @Path("tier") String paramString); var uri = $"https://rest-{baseData.LoginTier}.immedia-semi.com/api/v4/account/login"; var retString = await FirePostCallAsync(uri, loginBody, null); var ret = JsonConvert.DeserializeObject <LoginResponse>(retString); return(ret); }
public async Task Login_ShouldReturnBadRequestResult_WhenCredentialsFailValidation() { // Arrange LoginBody credentials = new LoginBody(); SessionController controller = new SessionController(null, null); controller.ModelState.AddModelError("Credentials", "Required"); // Act ActionResult <AuthenticatedUserResource> response = await controller.Login(credentials); // Assert Assert.IsType <BadRequestObjectResult>(response.Result); }
//public void LoginOld( Action<bool> callback = null) //{ // //UIManager.Inst.NetMask(true); // loginStatus = LoginStatus.LOGINING; // Dictionary<string, string> headerDic = new Dictionary<string, string>(); // string timeStr = ((int)SystemClock.Now).ToString(); // headerDic["appid"] = GameConfig.Inst.Appid; // headerDic["time"] = timeStr; // headerDic["devId"] = DeviceHelper.GetDeviceId(); // headerDic["pver"] = GameConfig.Inst.Pver; // headerDic["sign"] = Framework.Asset.AssetUtils.EncryptWithMD5(GameConfig.Inst.Appid + timeStr + Header.ClientKey); // LoginBody body = new LoginBody(URLConfig.Login); // body.type = "guest"; // //facebook的相关数据 // if (!string.IsNullOrEmpty(fbid)) // { // body.id = fbid; // body.type = "facebook"; // body.thirdtoken = "fbtoken_12345"; // } // body.deviceId = DeviceHelper.GetDeviceId(); // body.appid = GameConfig.Inst.Appid; // body.time = timeStr; // body.sign = headerDic["sign"]; // body.pver = headerDic["pver"]; // body.device = DeviceInfo.deviceInfo.ToString(); // Header header = Header.GetHeader(headerDic); // HttpRequestTool.SendMessage( // body, // (x) => { // Debug.Log("Login Sucess :" + x); // JSONNode respons = JSONNode.Parse(x); // string session = respons["session"]; // int code = respons["code"]; // int uid = respons["userInfo"]["gameUid"];//respons["pid"]; // string type = respons["type"]; // string id = respons["id"]; // DebugUtil.Log("=========serverUId:"+uid); // //UIManager.Inst.NetMask(false); // if (!string.IsNullOrEmpty(session)) // Session = session; // if(code == 0 && uid > 0) // StartCoroutine(OnReceiveServerData(respons["playdata"],uid,id,type,callback)); // else // loginStatus = LoginStatus.LOGINFAIL; // }, // (x) => { // //UIManager.Inst.NetMask(false); // Debug.LogError("Login Fail :" + x); // if (callback != null) // callback.Invoke(false); // loginStatus = LoginStatus.LOGINFAIL; // }, // header, // false); //} public LoginBody GetLoginBody() { LoginBody body = new LoginBody(URLConfig.Login); //facebook的相关数据 if (!string.IsNullOrEmpty(fbid)) { body.id = fbid; body.type = "facebook"; } body.deviceId = DeviceInfo.deviceInfo.deviceId; body.ip = DeviceHelper.GetIP(DeviceHelper.ADDRESSFAM.IPv4); body.country = DeviceInfo.deviceInfo.devicecountry; body.appBuildNum = DeviceInfo.deviceInfo.appvercode; return(body); }
/// <summary> /// 登录逻辑 /// </summary> /// <param name="loginData"></param> /// <param name="nodeId"></param> /// <param name="pDian"></param> /// <param name="vDian"></param> /// <returns></returns> public ResultMsg LoginValidate(LoginBody loginData, out int nodeId, out decimal pDian, out decimal vDian) { nodeId = 0; pDian = 0; vDian = 0; ResultMsg msg = new ResultMsg() { Success = true }; string appKey = ConfigurationManager.AppSettings["AppSign"]; if (string.IsNullOrEmpty(appKey)) { appKey = "af83f787e8911dea9b3bf677746ebac9"; } if (!Helper.CheckMd5(loginData.NodeCode + loginData.Pwd, loginData.Sign, appKey)) { msg.Success = false; msg.Message = "签名错误"; msg.Result = 0; return(msg); } PXinDb pXinDb = new PXinDb(); nodeId = pXinDb.LoginByNodeCode(loginData.NodeCode); if (nodeId == 0) { msg.Success = false; msg.Message = "账号不存在"; msg.Result = 0; return(msg); } if (pXinDb.CheckLockUser(nodeId)) { msg.Success = false; msg.Message = "用户已冻结"; msg.Result = 0; return(msg); } var userInfo = pXinDb.GetUserInfoByNodeId(nodeId); vDian = userInfo.V; pDian = userInfo.P; return(msg); }
public async Task <ActionResult> Login([FromBody] LoginBody body) { string username = body.Username.ToLower(); string hash = await db.Value <string>("SELECT hash FROM User WHERE LOWER(username)=@username", new { username }); if (!string.IsNullOrEmpty(hash) && crypto.HashCheck(hash, body.Password)) { JObject session = await LoadSession(username); session["token"] = GenerateJwtToken(session); return(Ok(session)); } return(Unauthorized("error.credentials")); }
public IActionResult Login([FromBody] LoginBody loginBody) { var user = userRepository.Login(loginBody.Email, loginBody.Senha); if (user == null) { apiError.Error = new Error { Code = Convert.ToInt16(StatusCodes.Status422UnprocessableEntity).ToString(), Message = "E-mail ou Senha errada." }; return(StatusCode(StatusCodes.Status422UnprocessableEntity, apiError)); } return(new ObjectResult(user)); }
async public Task <object> Login([FromBody] LoginBody body) { try { var user = await AuthModel.getUser(body.Email); if (user.Password != body.Password) { return(Unauthorized(new { error = "Invalid password" })); } return(Ok(user)); } catch (System.Exception e) { if (e.Message == "User doesn't exist") { return(Unauthorized(new { error = "Invalid email" })); } throw e; } }
public async Task <BaseResponse <LoginResult> > LoginAsync() { var body = new LoginBody { Email = _config.Email, Password = HashPassword(_config.Password), Method = "login" }; var response = await BaseUrl .AppendPathSegment("/cloud/v1/user/login") .WithHeader("Content-Type", "application/json") .PostJsonAsync(body) .ReceiveString(). ConfigureAwait(false); return(JsonConvert.DeserializeObject <BaseResponse <LoginResult> >(response)); }
public async Task <User> VerifyLogin(LoginBody loginBody) { // get the user by email User user = await userRepository.GetUserByEmail(loginBody.Email); // if the user does not exist if (user == null) { return(null); } // verify the password if (EncryptionUtil.Verify(loginBody.Password, user.Password, user.Salt)) { return(user); } return(null); }
public async Task <LoginResponse> Login([FromBody] LoginBody loginBody) { var Account = await _authenticationService.Login(loginBody.Email, loginBody.Password); if (Account == null) { return(null); } else { return(new LoginResponse { Token = _tokenService.CreateToken(Account.Id, Account.Role), Role = Account.Role.ToString(), Balance = Account.Balance, Name = loginBody.Email }); } }
public ActionResult <string> ApproveLogin([FromBody] LoginBody loginBody) { var user = _databaseContext.Users.Find(loginBody.Username); // return null if user not found if (user == null || user.Password != loginBody.Password) { return(BadRequest()); } var token = _identityService.Authenticate(user.Username); if (token != null) { return(Ok(new { token })); } // Else respond with Bad Request return(BadRequest()); }
async private void Button_Clicked(object sender, EventArgs e) { LoginBody loginBody = new LoginBody(); loginBody.Usuario = UserEntry.Text; loginBody.Password = PasswordEntry.Text; loginBody.Password = PasswordEntry.Text; LoginResponse loginResponse = LoginService.PostLogin(loginBody); if (loginResponse.EsPermitido) { Navigation.InsertPageBefore(new CarteleraPage(), this); await Navigation.PopAsync(); } else { await DisplayAlert("UPS!", loginResponse.Mensaje, "Aceptar"); } }
public async Task Login_ShouldReturnUser_WhenCredentialsAreValid() { // Arrange AuthenticatedUserResource expectedUser = new AuthenticatedUserResource() { UserId = 1 }; LoginBody credentials = new LoginBody { UserNameOrEmail = "myUsername", Password = "******" }; Mock <IMediator> mediatorMock = new Mock <IMediator>(); mediatorMock .Setup(m => m.Send(It.IsAny <LoginCommand>(), It.IsAny <CancellationToken>())) .ReturnsAsync(expectedUser); MapperConfiguration mapperConfiguration = new MapperConfiguration(config => { config.CreateMap <LoginBody, LoginCommand>(); }); IMapper mapperMock = mapperConfiguration.CreateMapper(); SessionController controller = new SessionController(mediatorMock.Object, mapperMock); // Act ActionResult <AuthenticatedUserResource> response = await controller.Login(credentials); // Assert OkObjectResult okResult = Assert.IsType <OkObjectResult>(response.Result); AuthenticatedUserResource actualUser = (AuthenticatedUserResource)okResult.Value; Assert.NotNull(actualUser); Assert.Equal(expectedUser.UserId, actualUser.UserId); }
public async Task <ActionResult <AuthenticatedUserResource> > Login([FromBody] LoginBody credentials, CancellationToken cancellationToken = default) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } LoginCommand command = _mapper.Map <LoginBody, LoginCommand>(credentials); AuthenticatedUserResource user = await _mediator.Send(command, cancellationToken); if (user == null) { return(Unauthorized(new ErrorResource { StatusCode = StatusCodes.Status401Unauthorized, Message = "UserName, e-mail and/or password are incorrect" })); } return(Ok(user)); }
/// <summary> /// logs in the user obtaining an auth token Creates a new group for the current user as owner. /// </summary> /// <param name="body"></param> /// <returns></returns> public IAsyncOperation LoginUser(LoginBody body) { // verify the required parameter 'body' is set if (body == null) { throw new ApiException(400, "Missing required parameter 'body' when calling LoginUser"); } var path = "/users/login"; path = path.Replace("{format}", "json"); var queryParams = new Dictionary <String, String>(); var headerParams = new Dictionary <String, String>(); var formParams = new Dictionary <String, String>(); var fileParams = new Dictionary <String, String>(); String postBody = null; postBody = ApiClient.Serialize(body); // http body (model) parameter // authentication setting, if any String[] authSettings = new String[] { "OAuth2" }; var result = new AsyncCompletionSource(); // make the HTTP request ApiClient.CallApi(path, UnityWebRequest.kHttpVerbPOST, queryParams, postBody, headerParams, formParams, fileParams, authSettings) .Then(webRequest => { result.SetCompleted(); }) .Catch(error => { var apiEx = (ApiException)error; result.SetException(new ApiException(apiEx.ErrorCode, "Error calling LoginUser: " + apiEx.Message, apiEx.ErrorContent)); }); return(result); }
private async void AbbApply_Click(object sender, RoutedEventArgs e) { Control element = (Control)sender; try { element.IsEnabled = false; if (!await UpdateBaseUrlStatus()) { tblError.Text = "Cannot connect to server"; tblError.Visibility = Visibility.Visible; return; } LoginBody body = new LoginBody() { Username = tbxUsername.Text, Password = pbxPassword.Password, KeepLoggedIn = true, }; if (await api.Login(body)) { Frame.GoBack(); return; } tblError.Text = "Please enter a correct Username and password"; tblError.Visibility = Visibility.Visible; } finally { element.IsEnabled = true; } //Frame.GoBack(); }
public async Task <GameSeverIdentityResult> CreateGameServerIdentityToken(LoginBody login) { var gameServer = await(from gs in this.dbContext.GameServer join gsg in this.dbContext.GameServerGroup on gs.GroupId equals gsg.Id where gs.PrivateKey == login.GameServerPrivateKey && gsg.PrivateKey == login.GameServerGroupPrivateKey && gs.IsActive && gs.IsValid && gsg.IsActive && gsg.IsValid select new { Name = gs.Name, GameServerGroupIdentifier = gsg.Id, GameServerGroupPublicKey = gsg.PublicKey, GameServerIdentifier = gs.Id, GameServerPublicKey = gs.PublicKey }) .SingleOrDefaultAsync(); if (gameServer == null) { return(null); } var token = new JwtTokenBuilder() .AddSecurityKey(JwtSecurityKey.Create(this.configuration["IdentityService:IssuerSigningKey"])) .AddSubject(gameServer.Name) .AddIssuer(this.configuration["IdentityService:ValidIssuer"]) .AddAudience(this.configuration["IdentityService:ValidAudience"]) .AddClaim("GameServerGroupIdentifier", gameServer.GameServerGroupIdentifier.ToString()) .AddClaim("GameServerIdentifier", gameServer.GameServerIdentifier.ToString()) .AddExpiry(int.Parse(this.configuration["IdentityService:TokenExpiry"] ?? "60")) .Build(); return(new GameSeverIdentityResult(token.Value, gameServer.GameServerGroupPublicKey, gameServer.GameServerPublicKey)); }
public async Task <bool> Login(LoginBody body) { Uri uri = GetUri("/api/auth/login"); if (uri == null) { return(false); } try { using (HttpClient client = GetClient()) { using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri)) { request.Content = new HttpStringContent(JsonConvert.SerializeObject(body), UnicodeEncoding.Utf8, "application/json"); using (HttpResponseMessage response = await client.SendRequestAsync(request)) { if (!response.IsSuccessStatusCode) { return(false); } RawCookies = response.Headers.Where(p => p.Key == "set-cookie").Select(p => p.Value).ToArray(); return(true); } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); return(false); } }
public static LoginResponse PostLogin(LoginBody loginBody) { return(ApiHelper.Post <LoginResponse, LoginBody>("/api/Seguridad", loginBody)); }
public bool login([FromBody] LoginBody pid) { return(service.doesUserExist(pid.pid)); }