/// <inheritdoc/> public async Task <bool> LoginByPass(LoginByPassCredentials credentials) { using var client = _factory.CreateClient(HttpClients.WebSshClient); using var response = await client.PostAsync(UrlConstants.Login, credentials.AsStringContent()); if (!response.IsSuccessStatusCode) { var res = await response.Content.ReadAsStringAsync(); _message.Error(res); return(false); } var result = (await response.Content.ReadFromJsonAsync <AuthData>(JsonExtensions.JsonSerializerOptions)) !; await _localStorage.SetItem(LocalStorageConstants.AuthToken, result.AccessToken); await _localStorage.SetItem(LocalStorageConstants.AuthData, result); ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(result.UserName); _navigationManager.NavigateTo(PageUrlConstants.Index); return(true); }
private async void SaveDataInLocalStorage(AuthSuccessResponse data, string email) { await _localStorageService.SetItem("accessToken", data.AccessToken); await _localStorageService.SetItem("refreshToken", data.RefreshToken); await _localStorageService.SetItem("email", email); }
public async Task <dynamic> Login(User user) { var content = await HelpPost("v1/account/login", user); var result = JsonConvert.DeserializeObject <dynamic>(content); var userResult = JsonConvert.DeserializeObject <User>(result["user"].ToString()); await _storage.SetItem("USER", userResult); return(result); }
public async Task Login(string email, string password) { var authenticateRequest = new AuthenticateRequest() { Email = email, Password = password }; var response = await _httpService.Post("api/users/authenticate", authenticateRequest); if (response.StatusCode == HttpStatusCode.Unauthorized) { _navigationManager.NavigateTo("authentication/logout"); return; } if (!response.IsSuccessStatusCode) { var error = await response.Content.ReadFromJsonAsync <Dictionary <string, string> >(); throw new Exception(error["message"]); } User = await response.Content.ReadFromJsonAsync <AuthenticateResponse>(); await _localStorageService.SetItem("user", User); }
public async Task Login(string username, string password) { User = await _httpService.Post <User>("/login", new { username, password }); User.AuthData = $"{username}:{password}".EncodeBase64(); await _localStorageService.SetItem(StaticValues.USERLS, User); }
public async Task SaveApiKey() { if (HasApiKey) { await LocalStorage.SetItem("GitterKey", apiKey); } }
public async Task Login(string username, string password) { User = await _httpService.Post <User>("/users/authenticate", new { username, password }); User.AuthData = $"{username}:{password}".EncodeBase64(); await _localStorageService.SetItem("user", User); }
public async Task SaveApiKey() { if (HasApiKey) { Console.WriteLine($"Storing ApiKey {apiKey}"); await LocalStorage.SetItem("GitterKey", apiKey); } }
private async Task SaveToken(HttpResponseMessage response) { var responseContent = await response.Content.ReadAsStringAsync(); var jwt = Json.Deserialize <JwToken>(responseContent); await _localStorage.SetItem("authToken", jwt.Token); }
public async Task Login(string email, string password) { User = await _httpService.Post <User>("/api/auth/driver/login", new { email, password }); await _localStorageService.SetItem("user", User); // Initialize web sockets connection await _webSocketService.InitializeWebSocketsAsync(User.Id); }
public async Task Login(string username, string password, RoleType roleType) { Auth = new Auth(); Auth.AuthData = $"{username}:{password}".EncodeBase64(); Auth.RoleType = roleType; await _localStorageService.SetItem("auth", Auth); if (Auth.RoleType == RoleType.Manager) { Manager manager = await _httpService.Get <Manager>("/users/Me"); await _localStorageService.SetItem("user", manager); } else if (Auth.RoleType == RoleType.Employee) { Employee manager = await _httpService.Get <Employee>("/users/Me"); await _localStorageService.SetItem("user", manager); } }
public void CreateSession(LoginResponse loginResponse) { if (loginResponse.Success) { _isLoggedIn = true; _localStorage.SetItem("isloggedin", true); LoginName = loginResponse.LoginName; EmailAddress = loginResponse.EmailAddress; DisplayName = loginResponse.DisplayName; } }
public async Task Login(string username, string password) { ///Do poprawy dzia³a ale najpierw powinienem pobraæ dane zeby sprawdziæ czy jest taki goœc i dopiero go zapisac w lokal User = new User() { AuthData = $"{username}:{password}".EncodeBase64() }; await _localStorageService.SetItem("user", User); UserData = await _httpService.Get <User>("/Users/me"); if (UserData != null) { await _localStorageService.SetItem("userData", UserData); } else { await _localStorageService.RemoveItem("user"); } }
public async Task Login(string email, string password) { User = await _httpService.Post <User>("/api/auth/customer/login", new { email, password }); await _localStorageService.SetItem("user", User); if (User != null) { Console.WriteLine("user ok"); // Initialize web sockets connection await _webSocketService.InitializeWebSocketsAsync(User.Id); _navigationManager.NavigateTo(""); } }
public async Task Login(Login model) { try { var result = await _httpService.Post <bool>("api/user/authenticate", model); Console.WriteLine("INitali called sdsdsdsd:" + result); User = new User(); await _localStorageService.SetItem(_userKey, User); } catch (Exception ex) { throw; } }
public async Task <(string result, bool isError)> LoginAsync(LoginModel model) { var result = await _client.Login.ExecuteAsync(new LoginModelInput { Username = model.Username, Password = model.Password }); if (result.IsErrorResult()) { return(string.Join('\n', result.Errors.Select(x => x.Message)), true); } var token = result.Data.Account.Login.ToString(); await _storageService.SetItem <string>("token", token); userClaims = new UserClaims(token); IsAuthenticated = true; return(token, false); }
public async Task Login(string email, string password) { try { Token = await _httpService.PostAsync <LoginResult>("api/users/tokens", new { email, password }); await _localStorageService.SetItem <LoginResult>("token", Token); } catch (HttpRequestException ex) { throw new Exception(ex.Data["StatusCode"] switch { HttpStatusCode.BadRequest => "Invalid login credentials.", HttpStatusCode.NotFound => "Invalid login credentials.", _ => "Something went wrong, please try again later." });
public async Task Login(LoginModel loginModel) { var r = await _httpClient.PostAsJsonAsync("https://localhost:44399/api/auth/login", loginModel); var response = r.Content.ReadFromJsonAsync <TokenModel>(); if (!String.IsNullOrEmpty(response.ToString())) { User = new TokenModel { Token = response.Result.Token, UserId = response.Result.UserId, UserName = response.Result.UserName, }; await _localStorageService.SetItem("tokenModel", User); } }
public async Task <OkResponse> UpdateModel(ClientSetting model) { _localStorage.SetItem(CommonVariables.ClientSettingsKey, model); Offline = model.OfflineMode; if (!Offline) { return new OkResponse() { Status = true } } ; if (string.IsNullOrEmpty(model.MatchId)) { return new OkResponse() { Status = false, Errors = new List <string>() { "Match id is null" } } } ; // clean up datas await _matchServiceIndexDb.DeleteAll <MatchContract>(); await _matchServiceIndexDb.DeleteAll <ShooterStageAggregationResult>(); await _matchServiceIndexDb.DeleteAll <ShooterMatchContract>(); await _matchServiceIndexDb.DeleteAll <ShooterSOStageContract>(); // download everything about model.MatchId var response = await _httpService.Post <MatchDataAssociationContract>("api/Aggregation/FetchDataForMatch", new MatchRequest { MatchId = model.MatchId }); if (response is not { WentWell : true })
public async Task <LoginResult> Login(LoginModel loginModel) { var loginAsJson = JsonSerializer.Serialize(loginModel); var response = await _httpClient.PostAsync("api/Login", new StringContent(loginAsJson, Encoding.UTF8, "application/json")); var loginResult = JsonSerializer.Deserialize <LoginResult>(await response.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (!response.IsSuccessStatusCode) { return(loginResult); } await _localStorage.SetItem("authToken", loginResult.Token); ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(loginModel.Email); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.Token); return(loginResult); }
public async Task SignInAsync(LoginDto dto) { var content = new StringContent(JsonSerializer.Serialize(dto), Encoding.UTF8, "application/json"); var responce = await _httpClient.PostAsync("https://localhost:4001/account/signin", content); if (responce.IsSuccessStatusCode) { var responceContent = await responce.Content.ReadAsStringAsync(); var userDto = JsonSerializer.Deserialize <AuthDto>(responceContent); User = new User { UserName = userDto.UserName, Token = userDto.Token }; await _localStorageService.SetItem("user", User); _navigationManager.NavigateTo("/"); } throw new NotImplementedException(); }
public async Task Login(Login model) { User = await _httpService.Post <User>("/users/authenticate", model); await _localStorageService.SetItem(_userKey, User); }
public async Task Login(string username, string password) { User = await _httpService.Post <User>("/api/authenticate", new { username, password }); await _localStorageService.SetItem("user", User); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // array in local storage for registered users var usersKey = "blazor-registration-login-example-users"; var users = await _localStorageService.GetItem <List <UserRecord> >(usersKey) ?? new List <UserRecord>(); var method = request.Method; var path = request.RequestUri.AbsolutePath; return(await handleRoute()); async Task <HttpResponseMessage> handleRoute() { if (path == "/users/authenticate" && method == HttpMethod.Post) { return(await authenticate()); } if (path == "/users/register" && method == HttpMethod.Post) { return(await register()); } if (path == "/users" && method == HttpMethod.Get) { return(await getUsers()); } if (Regex.Match(path, @"\/users\/\d+$").Success&& method == HttpMethod.Get) { return(await getUserById()); } if (Regex.Match(path, @"\/users\/\d+$").Success&& method == HttpMethod.Put) { return(await updateUser()); } if (Regex.Match(path, @"\/users\/\d+$").Success&& method == HttpMethod.Delete) { return(await deleteUser()); } // pass through any requests not handled above return(await base.SendAsync(request, cancellationToken)); } // route functions async Task <HttpResponseMessage> authenticate() { var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <Login>(bodyJson); var user = users.FirstOrDefault(x => x.Username == body.Username && x.Password == body.Password); if (user == null) { return(await error("Username or password is incorrect")); } return(await ok(new { Id = user.Id.ToString(), Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, Token = "fake-jwt-token" })); } async Task <HttpResponseMessage> register() { var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <AddUser>(bodyJson); if (users.Any(x => x.Username == body.Username)) { return(await error($"Username '{body.Username}' is already taken")); } var user = new UserRecord { Id = users.Count > 0 ? users.Max(x => x.Id) + 1 : 1, Username = body.Username, Password = body.Password, FirstName = body.FirstName, LastName = body.LastName }; users.Add(user); await _localStorageService.SetItem(usersKey, users); return(await ok()); } async Task <HttpResponseMessage> getUsers() { if (!isLoggedIn()) { return(await unauthorized()); } return(await ok(users.Select(x => basicDetails(x)))); } async Task <HttpResponseMessage> getUserById() { if (!isLoggedIn()) { return(await unauthorized()); } var user = users.FirstOrDefault(x => x.Id == idFromPath()); return(await ok(basicDetails(user))); } async Task <HttpResponseMessage> updateUser() { if (!isLoggedIn()) { return(await unauthorized()); } var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <EditUser>(bodyJson); var user = users.FirstOrDefault(x => x.Id == idFromPath()); // if username changed check it isn't already taken if (user.Username != body.Username && users.Any(x => x.Username == body.Username)) { return(await error($"Username '{body.Username}' is already taken")); } // only update password if entered if (!string.IsNullOrWhiteSpace(body.Password)) { user.Password = body.Password; } // update and save user user.Username = body.Username; user.FirstName = body.FirstName; user.LastName = body.LastName; await _localStorageService.SetItem(usersKey, users); return(await ok()); } async Task <HttpResponseMessage> deleteUser() { if (!isLoggedIn()) { return(await unauthorized()); } users.RemoveAll(x => x.Id == idFromPath()); await _localStorageService.SetItem(usersKey, users); return(await ok()); } // helper functions async Task <HttpResponseMessage> ok(object body = null) { return(await jsonResponse(HttpStatusCode.OK, body ?? new {})); } async Task <HttpResponseMessage> error(string message) { return(await jsonResponse(HttpStatusCode.BadRequest, new { message })); } async Task <HttpResponseMessage> unauthorized() { return(await jsonResponse(HttpStatusCode.Unauthorized, new { message = "Unauthorized" })); } async Task <HttpResponseMessage> jsonResponse(HttpStatusCode statusCode, object content) { var response = new HttpResponseMessage { StatusCode = statusCode, Content = new StringContent(JsonSerializer.Serialize(content), Encoding.UTF8, "application/json") }; // delay to simulate real api call await Task.Delay(500); return(response); } bool isLoggedIn() { return(request.Headers.Authorization?.Parameter == "fake-jwt-token"); } int idFromPath() { return(int.Parse(path.Split('/').Last())); } dynamic basicDetails(UserRecord user) { return(new { Id = user.Id.ToString(), Username = user.Username, FirstName = user.FirstName, LastName = user.LastName }); } }
public async Task Login(string username, string password) { try { /* * Uri uri = new Uri(_httpClient.BaseAddress + "login"); * LoginModel userlogin = new LoginModel() { UserName = username, Password = password }; * string json = Newtonsoft.Json.JsonConvert.SerializeObject(userlogin); * StringContent stringContent = new StringContent(json, Encoding.UTF8, StaticValues.APP_JSON); * _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(StaticValues.APP_JSON)); * _httpClient.DefaultRequestHeaders.Add(StaticValues.APP_CORS, "*"); * HttpResponseMessage response = await _httpClient.PostAsync(uri, stringContent); */ var requestMessage = new HttpRequestMessage() { Method = new HttpMethod("POST"), RequestUri = new Uri(_httpClient.BaseAddress + "login"), Content = JsonContent.Create(new LoginModel { UserName = username, Password = password }) }; //requestMessage.Headers.Add(StaticValues.APP_CORS, "*"); HttpResponseMessage response = await _httpClient.SendAsync(requestMessage); bool success = response.IsSuccessStatusCode; if (!success) { return; } string bearer = await response.Content.ReadAsStringAsync(); await _localStorageService.SetItem(StaticValues.BEARER, bearer); Console.WriteLine("Logined"); /* * requestMessage = new HttpRequestMessage() * { * Method = new HttpMethod("GET"), * RequestUri = new Uri(_httpClient.BaseAddress + "api/systemusers/" + username) * }; * requestMessage.Headers.Add(StaticValues.APP_CORS, "*"); * requestMessage.Headers.Add(StaticValues.Authorization, StaticValues.BEARER + " " + bearer); * //requestMessage.Headers.Add(StaticValues.COOKIE, cookie); // Blazor WASM do not allowed cookie * response = await _httpClient.SendAsync(requestMessage); * if (!success) return; * * string content = await response.Content.ReadAsStringAsync(); * UserLogin usr = Newtonsoft.Json.JsonConvert.DeserializeObject<UserLogin>(content); * usr.Bearer = bearer; */ User usr = await Get <User>("api/systemusers/" + username); usr.AuthData = $"{username}:{password}".EncodeBase64(); await _localStorageService.SetItem(StaticValues.USERLS, usr); Console.WriteLine(usr.UserName); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public async Task Login(string username, string password) { cliente = await _httpService.Post <Cliente>($"http://localhost:5000/Api/Clientes/authenticate", new { username, password }); await _localStorageService.SetItem("Clientes", cliente); }
public async Task Login(Clients model) { Client = await _httpService.Post <Clients>("/api/clients/authenticate", model); await _localStorageService.SetItem(_ClientKey, Client); }
//Access Token Implementation public async Task SetAccessTokenAsync(string accessToken) => await _localStorage.SetItem("authToken", accessToken);
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // array in local storage for registered Clients var ClientsKey = "ClientsXPTO"; var Clients = await _localStorageService.GetItem <List <ClientRecord> >(ClientsKey) ?? new List <ClientRecord>(); var method = request.Method; var path = request.RequestUri.AbsolutePath; return(await handleRoute()); async Task <HttpResponseMessage> handleRoute() { if (path == "/api/clients/authenticate" && method == HttpMethod.Post) { return(await authenticate()); } if (path == "/api/clients/register" && method == HttpMethod.Post) { return(await register()); } if (path == "/api/clients" && method == HttpMethod.Get) { return(await getClients()); } if (Regex.Match(path, @"\/api/clients\/\d+$").Success&& method == HttpMethod.Get) { return(await getClientById()); } if (Regex.Match(path, @"\/api/clients\/\d+$").Success&& method == HttpMethod.Put) { return(await updateClient()); } if (Regex.Match(path, @"\/api/clients\/\d+$").Success&& method == HttpMethod.Delete) { return(await deleteClient()); } // pass through any requests not handled above return(await base.SendAsync(request, cancellationToken)); } // route functions async Task <HttpResponseMessage> authenticate() { var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <Clients>(bodyJson); var Client = Clients.FirstOrDefault(x => x.Email == body.Email && x.Password == body.Password); if (Client == null) { return(await error("Email or password is incorrect")); } return(await ok(new { Id = Client.Id.ToString(), Username = Client.Username, Email = Client.Email, FullName = Client.FullName, BillingAddress = Client.BillingAddress, ShippingAddress = Client.ShippingAddress, Country = Client.Country, Phone = Client.Phone, Token = "fake-jwt-token" })); } async Task <HttpResponseMessage> register() { var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <Clients>(bodyJson); if (Clients.Any(x => x.Email == body.Email)) { return(await error($"Client email '{body.Email}' is already taken")); } var Client = new ClientRecord { Id = (Clients.Count() > 0) ? Clients.Max(x => x.Id) + 1 : 1, Username = body.Username, Email = body.Email, Password = body.Password, FullName = body.FullName, BillingAddress = body.BillingAddress, ShippingAddress = body.ShippingAddress, Country = body.Country, Phone = body.Phone }; Clients.Add(Client); await _localStorageService.SetItem(ClientsKey, Clients); return(await ok()); } async Task <HttpResponseMessage> getClients() { if (!isLoggedIn()) { return(await unauthorized()); } return(await ok(Clients.Select(x => basicDetails(x)))); } async Task <HttpResponseMessage> getClientById() { if (!isLoggedIn()) { return(await unauthorized()); } var Client = Clients.FirstOrDefault(x => x.Id == idFromPath()); return(await ok(basicDetails(Client))); } async Task <HttpResponseMessage> updateClient() { if (!isLoggedIn()) { return(await unauthorized()); } var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <Clients>(bodyJson); var Client = Clients.FirstOrDefault(x => x.Id == idFromPath()); // if Clientname changed check it isn't already taken if (Client.Email != body.Email && Clients.Any(x => x.Email == body.Email)) { return(await error($"Client email '{body.Email}' is already taken")); } // only update password if entered if (!string.IsNullOrWhiteSpace(body.Password)) { Client.Password = body.Password; } // update and save Client Client.Email = body.Email; Client.Username = body.Username; Client.FullName = body.FullName; Client.BillingAddress = body.BillingAddress; Client.ShippingAddress = body.ShippingAddress; Client.Country = body.Country; Client.Phone = body.Phone; await _localStorageService.SetItem(ClientsKey, Clients); return(await ok()); } async Task <HttpResponseMessage> deleteClient() { if (!isLoggedIn()) { return(await unauthorized()); } Clients.RemoveAll(x => x.Id == idFromPath()); await _localStorageService.SetItem(ClientsKey, Clients); return(await ok()); } // helper functions async Task <HttpResponseMessage> ok(object body = null) { return(await jsonResponse(HttpStatusCode.OK, body ?? new { })); } async Task <HttpResponseMessage> error(string message) { return(await jsonResponse(HttpStatusCode.BadRequest, new { message })); } async Task <HttpResponseMessage> unauthorized() { return(await jsonResponse(HttpStatusCode.Unauthorized, new { message = "Unauthorized" })); } async Task <HttpResponseMessage> jsonResponse(HttpStatusCode statusCode, object content) { var response = new HttpResponseMessage { StatusCode = statusCode, Content = new StringContent(JsonSerializer.Serialize(content), Encoding.UTF8, "application/json") }; // delay to simulate real api call await Task.Delay(500); return(response); } bool isLoggedIn() { return(request.Headers.Authorization?.Parameter == "fake-jwt-token"); } int idFromPath() { return(int.Parse(path.Split('/').Last())); } dynamic basicDetails(ClientRecord Client) { return(new { Id = Client.Id.ToString(), Username = Client.Username, Email = Client.Email, Password = Client.Password, FullName = Client.FullName, BillingAddress = Client.BillingAddress, ShippingAddress = Client.ShippingAddress, Country = Client.Country, Phone = Client.Phone }); } }
public async Task Login(LoginUser user) { User = await _httpService.Post <User>("/api/authenticate/login", user); await _localStorageService.SetItem(UserKey, User); }