public HttpResponseMessage Post(LoginRequest loginRequest) { var user = _context.Users.AsNoTracking().SingleOrDefault(a => a.Email == loginRequest.email); if (user != null) { if (user.Blocked) { return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_USER_BLOCKED))); } var incoming = AuthUtils.Hash(loginRequest.password, user.Salt); if (user.SaltedAndHashedPassword != null) { if (AuthUtils.SlowEquals(incoming, user.SaltedAndHashedPassword)) { var claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginRequest.email)); var loginResult = new StandartLoginProvider(Handler).CreateLoginResult(claimsIdentity, Services.Settings.MasterKey); return(Request.CreateResponse(HttpStatusCode.OK, loginResult)); } return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_LOGIN_INVALID_PASS))); } return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_LOGIN_INVALID_PASS))); } return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_LOGIN_INVALID_EMAIL))); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, [CosmosDB("ProjetWeb", "Users", ConnectionStringSetting = "CosmosDB")] DocumentClient users, ILogger log) { string bearer = req.Headers["Authorization"]; var authHeader = AuthUtils.GetClaims(bearer.Substring(7)); Models.User foundUser = UserUtils.GetUserFromEmail(users, authHeader["email"].ToString()); if (foundUser == null) { var notFoundResponse = new BaseResponse <object>(); notFoundResponse.Errors.Add("Utilisateur non trouvé."); var notFoundResult = new OkObjectResult(notFoundResponse) { StatusCode = StatusCodes.Status401Unauthorized }; return(notFoundResult); } return(new OkObjectResult(new BaseResponse <UserDto>(_mapper.Map <UserDto>(foundUser)))); }
/// <summary> /// Gets a list of <see cref="Contact"/> objects from Graph. /// </summary> /// <returns>A view with the list of <see cref="Contact"/> objects.</returns> public ActionResult Index() { //Get the access token as we need it to make a call to the Graph API string accessToken = AuthUtils.GetAuthToken(Request, HttpContext); if (accessToken == null) { // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } //Setup Graph API connection and get a list of users Guid ClientRequestId = Guid.NewGuid(); GraphSettings graphSettings = new GraphSettings(); graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion; GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings); PagedResults <Contact> pagedResults = graphConnection.List <Contact>(null, new FilterGenerator()); return(View(pagedResults.Results)); }
public ActionResult SignUp(User user) { if (ModelState.IsValid) { var userInDb = unitOfWork.Users.GetByCredentials(user.UserName); if (userInDb != null) { ModelState.AddModelError("UserName", "User Name allready exist."); return(View("LoginForm")); } var newUser = new User { UserName = user.UserName, Password = AuthUtils.GenerateBase64HashPassword(user.Password), BirthDate = user.BirthDate }; var cookie = AuthUtils.GenerateCookie(newUser); Response.Cookies.Add(cookie); unitOfWork.Users.Add(newUser); unitOfWork.Save(); ModelState.Clear(); return(RedirectToAction("Index", "Home")); } return(View()); }
public async Task <IActionResult> Register(string email, string password /*[FromBody] AuthUser model*/) { var authUser = _authUsers.SingleOrDefault(u => u.Email == email); if (authUser != null) { return(BadRequest(new { Status = "Error", Message = "User already exists!" })); } string hashText = AuthUtils.GenerateHashedPassword(password); authUser = new AuthUser { Email = email, Password = hashText, UserRole = "User" }; try { await _unitOfWork.UserRepository.AddAsync(authUser); await _unitOfWork.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.Message)); } return(Ok(authUser)); }
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity <TestCenter>() .HasMany(u => u.AvailableInCampaigns); modelBuilder.Entity <Campaign>() .HasMany(u => u.AvailableTestCenters); base.OnModelCreating(modelBuilder); modelBuilder.Entity <AuthRole>().HasData(new AuthRole { Id = 1, Name = "Admin" }); modelBuilder.Entity <AuthRole>().HasData(new AuthRole { Id = 2, Name = "User" }); modelBuilder.Entity <AuthUser>().HasData(new AuthUser { Id = 1, UserRole = "Admin", Email = "*****@*****.**", Password = AuthUtils.GenerateHashedPassword("*****@*****.**") }); modelBuilder.Entity <AuthUser>().HasData(new AuthUser { Id = 2, UserRole = "User", Email = "*****@*****.**", Password = AuthUtils.GenerateHashedPassword("*****@*****.**") }); }
public async Task <IActionResult> ChangePassword(ChangePasswordRequest req) { if (HttpContext.User.IsAnonymous()) { return(Challenge()); } if (!ModelState.IsValid) { return(View()); } var user = await Db.Users .SingleOrDefaultAsync(x => x.Id == HttpContext.User.GetUserId()); byte[] newHash = AuthUtils.GetHashFor(req.OldPassword, user.PasswordSalt); if (!Enumerable.SequenceEqual(newHash, user.PasswordHash)) { ModelState.AddModelError("", "Incorrect password"); return(View()); } user.PasswordSalt = AuthUtils.GetRandomData(64); user.PasswordHash = AuthUtils.GetHashFor(req.NewPassword, user.PasswordSalt); await Db.SaveChangesAsync(); return(RedirectToAction("News", "Issue")); }
public async Task <(bool success, string failureMessage)> LoginAsync(string account, string password) { var url = GetCliUrl(RestUrlLogin); var(success, result, _) = await RestUtils.PostAsync <LoginRequest, LoginResult>(url, new LoginRequest { Account = account, Password = AuthUtils.Md5ByString(password), IsPersistent = true }); if (!success) { return(false, "your account or password was incorrect"); } var status = new ConfigStatus { UserName = result.UserName, AccessToken = result.AccessToken }; await _configService.SaveStatusAsync(status); return(true, null); }
/// <summary> /// Creates a view to delete an existing <see cref="User"/>. /// </summary> /// <param name="objectId">Unique identifier of the <see cref="User"/>.</param> /// <returns>A view of the <see cref="User"/> to be deleted.</returns> public ActionResult Delete(string objectId) { //Get the access token as we need it to make a call to the Graph API string accessToken = AuthUtils.GetAuthToken(Request, HttpContext); if (accessToken == null) { // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } try { // Setup Graph API connection and get single User Guid ClientRequestId = Guid.NewGuid(); GraphSettings graphSettings = new GraphSettings(); graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion; GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings); User user = graphConnection.Get <User>(objectId); return(View(user)); } catch (Exception exception) { ModelState.AddModelError("", exception.Message); return(View()); } }
public void AuthenticateCommand_PresentWrongPassword_ThrowsException() { // ---- Arrange ---- const string email = "*****@*****.**"; const string name = "Test user"; const string wrongPassword = "******"; const string password = "******"; var passwordHash = AuthUtils.GetMd5Hash(password); var testUser = new UserIdentityModel( Guid.NewGuid(), email, "Test user", name, passwordHash, Instant.MinValue); _authRepositoryMock.Setup(r => r.GetUserIdentity(email)) .ReturnsAsync(() => testUser); var command = new AuthenticateUserCommand(email, wrongPassword); var handler = new AuthenticateUserCommandHandler(_repositoryProviderMock.Object, _configuration); // ---- Act & Assert ---- Assert.ThrowsAsync <WrongPasswordException>( async() => await handler.Handle(command, CancellationToken.None)); _authRepositoryMock.Verify(r => r.GetUserIdentity(email), Times.Once); }
public MediaController(ILogger <DeckController> logger, IFileRepository fileRepository, ContentSaver contentSaver, AuthUtils authUtils) { this.logger = logger; this.fileRepository = fileRepository; this.contentSaver = contentSaver; this.authUtils = authUtils; }
public virtual void Run() { Log.V(Tag, "{0}: RemoteRequest run() called, url: {1}".Fmt(this, url)); HttpClient httpClient = null; try { httpClient = clientFactory.GetHttpClient(); //var manager = httpClient.GetConnectionManager(); var authHeader = AuthUtils.GetAuthenticationHeaderValue(Authenticator, requestMessage.RequestUri); if (authHeader != null) { httpClient.DefaultRequestHeaders.Authorization = authHeader; } requestMessage.Headers.Add("Accept", "multipart/related, application/json"); AddRequestHeaders(requestMessage); SetBody(requestMessage); ExecuteRequest(httpClient, requestMessage); Log.V(Tag, "{0}: RemoteRequest run() finished, url: {1}".Fmt(this, url)); } finally { if (httpClient != null) { httpClient.Dispose(); } } }
private SdkAuthResult Auth() { try { if (AuthUtils.UseMsiAuth) { return(AuthUtils.RefreshMsiAuth()); } else { if (AuthUtils.UserHasNeverLoggedIn) { // User has not authenticated string cmdletName = $"{PowerShellCmdlets.Connect.CmdletVerb}-{PowerShellCmdlets.Connect.CmdletNoun}"; throw new PSAuthenticationError( new InvalidOperationException($"Not authenticated. Please use the \"{cmdletName}\" command to authenticate."), "NotAuthenticated", ErrorCategory.AuthenticationError, null); } // Refresh the token if required return(AuthUtils.RefreshAdalAuth()); } } catch (AdalException ex) { // Catch and bubble up any ADAL failures (this should never happen) throw new PSAuthenticationError( ex, "AuthenticationExpired", ErrorCategory.AuthenticationError, "Failed to obtain access token"); } }
public ActionResult Create([Bind(Include = "DisplayName,Description,MailNickName,SecurityEnabled")] Group group) { //Get the access token as we need it to make a call to the Graph API string accessToken = AuthUtils.GetAuthToken(Request, HttpContext); if (accessToken == null) { // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } try { // Setup Graph API connection and add Group Guid ClientRequestId = Guid.NewGuid(); GraphSettings graphSettings = new GraphSettings(); graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion; GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings); group.MailEnabled = false; graphConnection.Add(group); return(RedirectToAction("Index")); } catch (Exception exception) { ModelState.AddModelError("", exception.Message); return(View()); } }
public ActionResult OnPost() { if (!ModelState.IsValid) { return(Page()); } //var user = await _userManager.FindByNameAsync(AuthUser.Email); //if (user != null) //{ // ModelState.AddModelError(string.Empty, "Register not succeeded!"); // return Page(); //} AuthUser newUser = new AuthUser { Email = AuthUser.Email, Password = AuthUtils.GenerateHashedPassword(AuthUser.Password), UserRole = "User" }; LoginModel.AddUser(newUser); return(RedirectToPage("/Index")); }
public void ValidateEmailMethod_PresentValidEmail_ReturnsTrue() { // ---- Arrange ---- var validEmails = new List <string>() { "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "[email protected]", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**" }; // ---- Act & Assert ---- foreach (var email in validEmails) { Assert.IsTrue(AuthUtils.ValidateEmail(email), $"Email: {email}"); } }
public IActionResult PostNewUser(string eMail, string password) { if (string.IsNullOrEmpty(eMail) || string.IsNullOrEmpty(password)) { return(BadRequest()); } var newAuthUser = new AuthUser { Email = eMail, Password = AuthUtils.GenerateHashedPassword(password), Role = "User" }; _users.Add(newAuthUser); //try //{ // await _unitOfWork.Users.AddAsync(newAuthUser); // await _unitOfWork.SaveChangesAsync(); //} //catch (Exception ex) //{ // return BadRequest(ex.Message); //} //_users.Add(newAuthUser); return(NoContent()); }
public void ValidateEmailMethod_PresentWrongFormattedEmail_ReturnFalse() { // ---- Arrange ---- var invalidEmails = new List <string>() { "plainaddress", "#@%^%#$@#$@#.com", "@example.com", "Artem Spirex <*****@*****.**>", "email.example.com", "email@[email protected]", "A@b@[email protected]", "*****@*****.**", "*****@*****.**", "*****@*****.**", "あいうえお@example.com", "[email protected] (Artem SpireX)", "email@example", "*****@*****.**", "*****@*****.**", "*****@*****.**", "(),\":;<>[\\]@example.com", "just\"not\"*****@*****.**", "this\\ is\"really\"not\\[email protected]" }; foreach (var email in invalidEmails) { Assert.IsFalse(AuthUtils.ValidateEmail(email), $"Email: {email}"); } }
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, HttpCompletionOption option, CancellationToken token) { #if NET_3_5 if(_connectionCount >= _connectionLimit) { return Task.Delay(500).ContinueWith(t => SendAsync(message, option, token)).Unwrap(); } Interlocked.Increment(ref _connectionCount); #else return _sendSemaphore.WaitAsync().ContinueWith(t => { #endif var challengeResponseAuth = Authenticator as IChallengeResponseAuthenticator; if (challengeResponseAuth != null) { if (_authHandler != null) { _authHandler.Authenticator = challengeResponseAuth; } challengeResponseAuth.PrepareWithRequest(message); } var authHeader = AuthUtils.GetAuthenticationHeaderValue(Authenticator, message.RequestUri); if (authHeader != null) { _httpClient.DefaultRequestHeaders.Authorization = authHeader; } return _httpClient.SendAsync(message, option, token); #if !NET_3_5 }).Unwrap().ContinueWith(t => { _sendSemaphore.Release(); return t.Result; }); #endif }
/// <summary> /// Creates a view to for editing an existing <see cref="User"/> in Graph. /// </summary> /// <param name="objectId">Unique identifier of the <see cref="User"/>.</param> /// <returns>A view with details to edit <see cref="User"/>.</returns> public ActionResult Edit(string objectId) { //Get the access token as we need it to make a call to the Graph API string accessToken = AuthUtils.GetAuthToken(Request, HttpContext); if (accessToken == null) { // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } // Setup Graph API connection and get single User var clientRequestId = Guid.NewGuid(); var graphSettings = new GraphSettings { ApiVersion = GraphConfiguration.GraphApiVersion }; var graphConnection = new GraphConnection(accessToken, clientRequestId, graphSettings); var user = graphConnection.Get <User>(objectId); return(View(user)); }
public void TestGetAuthenticationHeaderValue() { var username1 = "username1"; var password1 = "password1"; var credParam1 = Convert.ToBase64String( Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username1, password1))); var auth = AuthenticatorFactory.CreateBasicAuthenticator(username1, password1); var authHeader = AuthUtils.GetAuthenticationHeaderValue(auth, null); Assert.IsNotNull(authHeader); Assert.AreEqual(credParam1, authHeader.Parameter); var username2 = "username2"; var password2 = "password2"; var credParam2 = Convert.ToBase64String( Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username2, password2))); var userinfo = username2 + ":" + password2; var uri = new Uri("http://" + userinfo + "@couchbase.com"); var request = new HttpRequestMessage(HttpMethod.Get, uri); authHeader = AuthUtils.GetAuthenticationHeaderValue(auth, request.RequestUri); Assert.IsNotNull(authHeader); Assert.AreEqual(credParam2, authHeader.Parameter); uri = new Uri("http://www.couchbase.com"); request = new HttpRequestMessage(HttpMethod.Get, uri); authHeader = AuthUtils.GetAuthenticationHeaderValue(null, request.RequestUri); Assert.IsNull(authHeader); auth = AuthenticatorFactory.CreateFacebookAuthenticator("1234"); authHeader = AuthUtils.GetAuthenticationHeaderValue(auth, null); Assert.IsNull(authHeader); }
public ActionResult Delete(User user) { //Get the access token as we need it to make a call to the Graph API string accessToken = AuthUtils.GetAuthToken(Request, HttpContext); if (accessToken == null) { // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } try { // Setup Graph API connection and delete User var clientRequestId = Guid.NewGuid(); var graphSettings = new GraphSettings { ApiVersion = GraphConfiguration.GraphApiVersion }; var graphConnection = new GraphConnection(accessToken, clientRequestId, graphSettings); graphConnection.Delete(user); return(RedirectToAction("Index")); } catch (Exception exception) { ModelState.AddModelError("", exception.Message); return(View(user)); } }
public static async Task <IActionResult> RunAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, [CosmosDB("ProjetWeb", "Users", ConnectionStringSetting = "CosmosDB")] DocumentClient users, ILogger log) { string bearer = req.Headers["Authorization"]; var authHeader = AuthUtils.GetClaims(bearer.Substring(7)); Models.User foundUser = UserUtils.GetUserFromEmail(users, authHeader["email"].ToString()); if (foundUser == null) { return(new UnauthorizedResult()); } var collectionUri = UriFactory.CreateDocumentCollectionUri("ProjetWeb", "Users"); var queryOptions = new FeedOptions { EnableCrossPartitionQuery = true }; var query = users.CreateDocumentQuery <Models.User>(collectionUri, queryOptions); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var data = JsonConvert.DeserializeObject <Models.Product>(requestBody); var newProduct = new Models.Product { id = data.id, Title = data.Title, Description = data.Description, Price = data.Price, Year = data.Year, HorsePower = data.HorsePower, Mileage = data.Mileage, Fuel = data.Fuel, Images = data.Images }; if (foundUser.Orders == null) { foundUser.Orders = new List <Models.Order>(); foundUser.Orders.Add(new Models.Order { Product = newProduct, IsPayed = true, OrderPlacedDate = DateTime.Now }); } foundUser.Orders.Add(new Models.Order { id = Guid.NewGuid().ToString(), Product = newProduct, IsPayed = true, OrderPlacedDate = DateTime.Now }); await users.UpsertDocumentAsync(collectionUri, foundUser); return(new OkObjectResult("OK")); }
/// <summary> /// Gets a list of <see cref="User"/> objects that a given <see cref="User"/> has as a direct report. /// </summary> /// <param name="objectId">Unique identifier of the <see cref="User"/>.</param> /// <returns>A view with the list of <see cref="User"/> objects.</returns> public ActionResult GetDirectReports(string objectId) { //Get the access token as we need it to make a call to the Graph API string accessToken = AuthUtils.GetAuthToken(Request, HttpContext); if (accessToken == null) { // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } // Setup Graph API connection and get Group membership Guid ClientRequestId = Guid.NewGuid(); GraphSettings graphSettings = new GraphSettings(); graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion; GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings); GraphObject graphUser = graphConnection.Get <User>(objectId); IList <GraphObject> results = graphConnection.GetAllDirectLinks(graphUser, LinkProperty.DirectReports); IList <User> reports = new List <User>(); foreach (GraphObject obj in results) { if (obj is User) { User user = (User)obj; reports.Add(user); } } return(View(reports)); }
public void Login() { var authenticated = false; var connectionId = CookieManager.GetConnectionId(_client); var password = _packet.Args[0].ToString(); authenticated = !string.IsNullOrEmpty(password) && AuthUtils.Authenticate(password); AuthClient authClient; UlteriusApiServer.AllClients.TryGetValue(connectionId, out authClient); if (authClient != null) { if (authClient.Authenticated) { _builder.WriteMessage(new { authenticated, message = "Already logged in." }); return; } authClient.Authenticated = authenticated; UlteriusApiServer.AllClients[connectionId] = authClient; } var authenticationData = new { authenticated, message = authenticated ? "Login was successful" : "Login was unsuccessful" }; _builder.WriteMessage(authenticationData); }
public ActionResult Create([Bind(Include = "UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department")] User user) { //Get the access token as we need it to make a call to the Graph API var accessToken = AuthUtils.GetAuthToken(Request, HttpContext); if (accessToken == null) { // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } try { // Setup Graph API connection and add User var clientRequestId = Guid.NewGuid(); var graphSettings = new GraphSettings { ApiVersion = GraphConfiguration.GraphApiVersion }; var graphConnection = new GraphConnection(accessToken, clientRequestId, graphSettings); graphConnection.Add(user); return(RedirectToAction("Index")); } catch (Exception exception) { ModelState.AddModelError("", exception.Message); return(View()); } }
public async Task <IActionResult> PostNewUser(string eMail, string password) { if (string.IsNullOrEmpty(eMail) || string.IsNullOrEmpty(password)) { return(BadRequest()); } AuthUser userInDb = await _unitOfWork.AuthUsers.GetByEmailAsync(eMail); if (userInDb != null) { return(BadRequest()); } var newAuthUser = new AuthUser { Email = eMail, Password = AuthUtils.GenerateHashedPassword(password), UserRole = "User" }; try { await _unitOfWork.AuthUsers.AddAsync(newAuthUser); await _unitOfWork.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.Message)); } //_users.Add(newAuthUser); return(NoContent()); }
public override void Run() { HttpClient httpClient = null; try { httpClient = clientFactory.GetHttpClient(); requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/related")); var authHeader = AuthUtils.GetAuthenticationHeaderValue(Authenticator, requestMessage.RequestUri); if (authHeader != null) { httpClient.DefaultRequestHeaders.Authorization = authHeader; } //TODO: implement gzip support for server response see issue #172 //request.addHeader("X-Accept-Part-Encoding", "gzip"); AddRequestHeaders(requestMessage); SetBody(requestMessage); ExecuteRequest(httpClient, requestMessage); } finally { if (httpClient != null) { httpClient.Dispose(); } } }
/// <summary> /// Gets details of a single <see cref="Contact"/> Graph. /// </summary> /// <returns>A view with the details of a single <see cref="Contact"/>.</returns> public ActionResult Details(string objectId) { //Get the access token as we need it to make a call to the Graph API string accessToken = AuthUtils.GetAuthToken(Request, HttpContext); if (accessToken == null) { // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } // Setup Graph API connection and get single Contact Guid ClientRequestId = Guid.NewGuid(); GraphSettings graphSettings = new GraphSettings(); graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion; GraphConnection graphConnection = new GraphConnection(accessToken, ClientRequestId, graphSettings); Contact contact = graphConnection.Get <Contact>(objectId); return(View(contact)); }
public async Task <(bool success, string failureMessage)> LoginAsync(string account, string password) { var client = new RestClient(CloudUtils.Api.GetCliUrl(RestUrlLogin)) { Timeout = -1 }; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", TranslateUtils.JsonSerialize(new LoginRequest { Account = account, Password = AuthUtils.Md5ByString(password), IsPersistent = true }), ParameterType.RequestBody); var response = client.Execute <LoginResult>(request); if (!response.IsSuccessful) { return(false, "your account or password was incorrect"); } var loginResult = response.Data; var status = new ConfigStatus { UserName = loginResult.UserName, AccessToken = loginResult.AccessToken }; await _configService.SaveStatusAsync(status); return(true, null); }