public async Task <AuthResponseModel> InsertBook(string title, string description, string author, int publishYear, string access) { string myJson = "{'title': '" + title + "', 'description' : '" + description + "', 'author':'" + author + "', 'publishYear' : " + publishYear + ", 'category' : 'book', 'access' : '" + access + "', 'authToken' : '" + ReferenceList.Token + "'}"; JsonData json = new JsonData(); var response = new AuthResponseModel(); using (var client = new HttpClient()) { var post = await client.PostAsync( ReferenceList.BookStaff, new StringContent(myJson, Encoding.UTF8, "application/json")); json = await post.Content.ReadAsStringAsync(); } try { json = JsonMapper.ToObject(json.ToString()); response.Response = (int)json["response"]; response.Status = json["status"].ToString(); response.Info = json["info"].ToString(); } catch (Exception e) { Console.WriteLine(e.GetBaseException().ToString()); } return(response); }
private async void UserRegisterAsync() { ComboBoxItem typeItem = (ComboBoxItem)CBUserType.SelectedItem; string type = typeItem.Content.ToString(); int userType; if (type == T1.Content.ToString()) //Local { userType = 1; } else //foreign { userType = 2; } UserProcessor processor = new UserProcessor(); AuthResponseModel response = new AuthResponseModel(); response = await processor.RegisterAsync(Username1.Text, Password1.Text, userType); if (response.Response.Equals(200)) { GridLogin.Visibility = Visibility.Visible; GridRegister.Visibility = Visibility.Hidden; MessageBox.Show("Account created successfully! \n If registed as foreign student, you'll have to wait for Librarian's approval."); } else { MessageBox.Show(response.Info); } }
public BaseResponseModel SignUp(SignUpInputModel inputModel) { var vm = new AuthResponseModel(); // Validate request var validationState = new ValidationDictionary(); inputModel.ValidateRequest(validationState); var user = new User { Email = inputModel.Email, Role = Role.Member }; UserService.GenerateUserPassword(user, inputModel.Password); if (UserService.ValidateUser(user, validationState)) { UserService.CreateUser(user); // Authenticate to create token user = UserService.Authenticate(user.Email, inputModel.Password); _auth.DoAuth(user.Email, false); vm.Success = true; vm.Token = user.AuthToken.Token; vm.Expires = user.AuthToken.Expires; } vm.Errors = validationState.Errors; return(vm); }
public async Task <AuthResponseModel> UpdateBook(int id, string type, string value) { string myJson = "{'id': '" + id + "', 'type' : '" + type + "', 'value':'" + value + "', 'authToken' : '" + ReferenceList.Token + "'}"; JsonData json = new JsonData(); var response = new AuthResponseModel(); using (var client = new HttpClient()) { var post = await client.PutAsync( ReferenceList.BookStaff, new StringContent(myJson, Encoding.UTF8, "application/json")); json = await post.Content.ReadAsStringAsync(); } try { json = JsonMapper.ToObject(json.ToString()); response.Response = (int)json["response"]; response.Status = json["status"].ToString(); response.Info = json["info"].ToString(); } catch (Exception e) { Console.WriteLine(e.GetBaseException().ToString()); } return(response); }
public async Task <AuthResponseModel> DeleteBook(int id) { JsonData json = new JsonData(); var response = new AuthResponseModel(); using (var client = new HttpClient()) { var post = await client.DeleteAsync( ReferenceList.BookStaff + $"{ReferenceList.Token}/{id}"); json = await post.Content.ReadAsStringAsync(); } try { json = JsonMapper.ToObject(json.ToString()); response.Response = (int)json["response"]; response.Status = json["status"].ToString(); response.Info = json["info"].ToString(); } catch (Exception e) { Console.WriteLine(e.GetBaseException().ToString()); } return(response); }
static async Task MainAsync() { var configuration = GetConfiguration(); SecureTradingConfigurationModel secureTradingConfig = new SecureTradingConfigurationModel { Alias = configuration["SecureTrading:Alias"], SiteReference = configuration["SecureTrading:SiteReference"], Endpoint = configuration["SecureTrading:Endpoint"], Username = configuration["SecureTrading:Username"], Password = configuration["SecureTrading:Password"], Version = "1.00" }; SecureTradingClient service = new SecureTradingClient(secureTradingConfig); var orderReference = Guid.NewGuid().ToString(); AuthResponseModel auth = await service.AuthAsync(new AuthRequestModel { BaseAmount = "1050", PAN = "4111111111111111", CVV = "123", Expiry = "12/2020", Currency = "GBP", OrderReference = orderReference, }); System.Console.WriteLine("Hello World!"); }
public async Task <AuthResponseModel> RegisterAsync(string username, string password, int userType) { string myJson = "{'UserName': '******', 'Email' : '*****@*****.**', 'Pass':'******', 'UserType' : " + userType + "}"; JsonData json = new JsonData(); var response = new AuthResponseModel(); using (var client = new HttpClient()) { var post = await client.PostAsync( ReferenceList.Register, new StringContent(myJson, Encoding.UTF8, "application/json")); json = await post.Content.ReadAsStringAsync(); } try { json = JsonMapper.ToObject(json.ToString()); response.Response = (int)json["response"]; response.Status = json["status"].ToString(); response.Info = json["info"].ToString(); } catch (Exception e) { Console.WriteLine(e.GetBaseException().ToString()); } return(response); }
public AuthResponseModel AddUserInfo(User usermodel) { AuthResponseModel model = new AuthResponseModel { isSuccess = false }; var userToUpdate = db.Users.FirstOrDefault(x => x.Username.Equals(usermodel.CurrentUserId)); if (userToUpdate != null) { userToUpdate.TimeFrom = usermodel.TimeFrom != null?TimeSpan.Parse(usermodel.TimeFrom.ToString()) : (TimeSpan?)null; userToUpdate.TimeTo = usermodel.TimeTo != null?TimeSpan.Parse(usermodel.TimeTo.ToString()) : (TimeSpan?)null; userToUpdate.DeviceId = usermodel.DeviceId; userToUpdate.Status = usermodel.Status; if (usermodel.ServicesList != null && usermodel.ServicesList.Count > 0) { foreach (int t in usermodel.ServicesList) { int serv_id = Convert.ToInt32(t); var service = db.Services.FirstOrDefault(x => x.Id == serv_id); if (service != null) { userToUpdate.Services.Add(service); } } } db.SaveChanges(); model.isSuccess = true; } return(model); }
private AuthResponseModel SetResponse(int decision) { var jsonResponse = new AuthResponseModel(); switch (decision) { case 0: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "Could not complete this action. Contact Administrator."; break; case 1: IsVerified = true; break; case 3: jsonResponse.Response = 500; jsonResponse.Status = "Error"; jsonResponse.Info = "Internal server error"; break; case 5: jsonResponse.Response = 200; jsonResponse.Status = "Success"; jsonResponse.Info = "Item added successfully!"; break; } return(jsonResponse); }
public BaseResponseModel SignIn(SignInInputModel inputModel) { var vm = new AuthResponseModel(); var user = UserService.Authenticate(inputModel.Email, inputModel.Password); if (user != null) { _auth.DoAuth(inputModel.Email, inputModel.RememberMe); vm.Success = true; vm.Token = user.AuthToken.Token; vm.Expires = user.AuthToken.Expires; } else { vm.Errors.Add("Invalid email or password"); LogService.CreateLog(new Log { Category = LogCategory.Security, IpAddress = GetClientIp(ControllerContext.Request), Level = LogLevel.Info, Message = "Authentication failed using email: " + inputModel.Email }); } return(vm); }
private AuthResponseModel SetResponse(int decision) { var jsonResponse = new AuthResponseModel(); switch (decision) { case 0: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "UserName already Taken"; break; case 1: IsVerified = true; break; case 2: IsValidated = true; break; case 3: jsonResponse.Response = 500; jsonResponse.Status = "Error"; jsonResponse.Info = "Internal server error"; break; case 4: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "Invalid format for username"; break; case 5: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "Invalid format for Email"; break; case 6: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "Invalid format for password"; break; case 7: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "User type should be either 1/2"; break; case 8: jsonResponse.Response = 200; jsonResponse.Status = "Successful"; jsonResponse.Info = "Registration successful!"; break; } return(jsonResponse); }
private async void DeleteItem() { var idText = TBDeleteItemId.Text; var response = new AuthResponseModel(); int id; if (!Regex.IsMatch(idText, @"^\d+$")) { MessageBox.Show("ID should be a number!"); return; } else { id = Convert.ToInt32(idText); } ComboBoxItem typeItem = (ComboBoxItem)CBDeleteItemCategory.SelectedItem; string category = typeItem.Content.ToString(); if (category == T31.Content.ToString()) //Books { BookProcessor book = new BookProcessor(); response = await book.DeleteBook(id); MessageBox.Show(response.Info); } else if (category == T32.Content.ToString()) //Newspapers { NewspaperProcessor newspaper = new NewspaperProcessor(); response = await newspaper.DeleteNewspaper(id); MessageBox.Show(response.Info); } else if (category == T33.Content.ToString()) //Journals { JournalProcessor journal = new JournalProcessor(); response = await journal.DeleteJournal(id); MessageBox.Show(response.Info); } else if (category == T34.Content.ToString()) //Magazines { MagazineProcessor magazine = new MagazineProcessor(); response = await magazine.DeleteMagazine(id); MessageBox.Show(response.Info); } else if (category == T35.Content.ToString()) //Manuscripts { ManuscriptProcessor manuscript = new ManuscriptProcessor(); response = await manuscript.DeleteManuscript(id); MessageBox.Show(response.Info); } }
public static OrderResponseTypeModel Map(AuthResponseModel dto) { return(new OrderResponseTypeModel { AutoStartToken = dto.AutoStartToken, OrderRef = dto.OrderRef, }); }
public static void AddAuthToken(HttpClient client, AuthResponseModel token) { if (client.DefaultRequestHeaders.Contains("Authorization")) { client.DefaultRequestHeaders.Remove("Authorization"); } client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token.AccessToken); }
public async Task <ActionResult> postAd(string iName, string iCategory, string iAvailable, string iLoc, IFormFile img, string iDescription, string iContact, string iPrice, string iCondition, string iNegotiable) { AdvertRepository ad = new AdvertRepository(); AuthResponseModel response = new AuthResponseModel(); int negotiable = 0; var filePath = Path.GetTempFileName(); string iimg = null; try { if (img.Length > 0) { using (var stream = new FileStream(filePath, FileMode.Create)) { await img.CopyToAsync(stream); } var bytes = System.IO.File.ReadAllBytes(filePath); iimg = Convert.ToBase64String(bytes); } } catch (Exception) { Stream imgStream = Assembly.GetExecutingAssembly() .GetManifestResourceStream( "DSProject.Resources.notfound.png"); var path1 = @"D:\MS_VS_Projects\DSProject\DSProject\WebSite\Resources\notfound.png"; var path2 = @"..\WebSite\Resources\notfound.png"; var bytes = System.IO.File.ReadAllBytes(path2); iimg = Convert.ToBase64String(bytes); } if (iNegotiable.Equals("Negotiable")) { negotiable = 1; } else { negotiable = 0; } response = await ad.AddAdvert(iName, iCategory, iAvailable, iLoc, iimg, iDescription, iContact, iPrice, iCondition, negotiable); if (response.Response.Equals(200)) { return(RedirectToAction("AdsPage")); } else { var rsp = new AuthResponseModel { Response = response.Response, Status = response.Status, Info = response.Info }; return(RedirectToAction("Home", "Home")); } }
public IActionResult Home(AuthResponseModel response) { ViewData["Response"] = response.Response; ViewData["Status"] = response.Status; ViewData["Info"] = response.Info; ViewBag.Name = HttpContext.Session.GetString(SessionName); return(View()); }
private AuthResponseModel SetResponse(int decision) { var jsonResponse = new AuthResponseModel(); switch (decision) { case 0: jsonResponse.Response = 401; jsonResponse.Status = "Error"; jsonResponse.Info = "User account is not active yet. Contact the librarian."; break; case 1: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "Auth failed"; break; case 2: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "Invalid username"; break; case 3: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "Invalid password"; break; case 4: jsonResponse.Response = 500; jsonResponse.Status = "Error"; jsonResponse.Info = "Internal server error"; break; case 5: jsonResponse.Response = 200; jsonResponse.Status = "Success"; jsonResponse.Token = GenerateUserToken(); jsonResponse.Value = UserRole; break; case 6: IsVerified = true; break; case 7: IsValidated = true; break; } return(jsonResponse); }
public async Task Login() { var headers = new Dictionary <string, string> { { AuthHeader, $"{BasicAuthType} {$"{authData.ClientId}:{authData.ClientSecret}".ToBase64()}" } }; var content = new StringContent($"grant_type=password&username={authData.Username}&password={authData.Password}&scope=web default rights claims openid", Encoding.UTF8, "application/x-www-form-urlencoded"); authResponse = await httpClient.Post(Routes.Login, content, headers); }
private AuthResponseModel SetResponse(int decision) { var jsonResponse = new AuthResponseModel(); switch (decision) { case -1: jsonResponse.Response = 401; jsonResponse.Status = "Error"; jsonResponse.Info = "No permission to complete this action."; break; case 0: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "Could not complete this action. Contact Administrator."; break; case 1: IsVerified = true; break; case 2: IsValidated = true; break; case 3: jsonResponse.Response = 500; jsonResponse.Status = "Error"; jsonResponse.Info = "Internal server error"; break; case 4: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "Auth Token is required to complete this action."; break; case 5: jsonResponse.Response = 403; jsonResponse.Status = "Error"; jsonResponse.Info = "<Id> is required"; break; case 6: jsonResponse.Response = 200; jsonResponse.Status = "Success"; jsonResponse.Info = "User Deleted successfully!"; break; } return(jsonResponse); }
public async Task <ActionResult <AuthResponseModel> > Login(UserAuthModel userAuthModel) { AuthResponseModel authResult = await _iAuthService.Value.Login(userAuthModel); if (authResult == null) { return(Unauthorized(new AuthResponseModel { ErrorMessage = "Invalid Authentication" })); } return(Ok(new Response <AuthResponseModel>(authResult))); }
/// <summary> /// Execute convert ouput. /// </summary> /// <param name="resultObject">DataModel</param> /// <returns>ResponseModel</returns> private AuthResponseModel Convert(AuthDataModel resultObject) { // Local variable declaration AuthResponseModel response = null; // Variable initialize response = new AuthResponseModel(); response.UserCd = DataHelper.ToString(resultObject.UserCd); response.UserName = DataHelper.ToString(resultObject.UserName); return(response); }
private async void AuthUser(string TOKEN) { try { string res = await this.http.GetAsync("http://192.168.0.184:5000/user/authenticate", TOKEN); AuthResponseModel response = JsonConvert.DeserializeObject <AuthResponseModel>(res); if (response.status) { this.UserIsValid(response.username); this.token = TOKEN; } } catch (Exception) { } }
protected async Task Authorize() { HttpResponseMessage response = await _client.PostAsJsonAsync("/api/Auth/LogIn", new LoginModel() { Email = "*****@*****.**", Password = "******" }); string content = await response.Content.ReadAsStringAsync(); AuthResponseModel responseModel = JsonConvert.DeserializeObject <AuthResponseModel>(content); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", responseModel.Token); }
private AuthResponseModel AuthenticateUser(AuthRequestModel login) { AuthResponseModel user = null; var authBL = new AuthBL(); var authenticateResult = authBL.AuthenticateUser(login); if (!authenticateResult.Status) { return(user); } user = authenticateResult.Value; return(user); }
public IActionResult Login([FromBody] LoginModel loginModel) { // try to login AuthResponseModel model = _service.Login(loginModel.Email, loginModel.Password); if (model == null) { // return a generic error message if not successful return(BadRequest(new { err = "Invalid Credintials" })); } // otherwise add cookies to the user's browser AddAuthCookies(model); return(Ok()); }
public IActionResult SignUp([FromBody] SignupModel signupModel) { // try to signup the user try { AuthResponseModel model = _service.Signup(signupModel.Email, signupModel.FirstName, signupModel.LastName, signupModel.Password); // add cookies to the user's browser AddAuthCookies(model); return(Ok()); } catch (ApplicationException e) { // return exceptions thrown from the user service return(BadRequest(new { err = e.Message })); } }
public async Task Login(string nameOrEmail, string password, CancellationToken cancellationToken = default) { AuthRequestModel authModel = new AuthRequestModel { NameOrEmail = nameOrEmail, Password = password }; string json = JsonConvert.SerializeObject(authModel); using (HttpClientHandler handler = GetHttpClientHandler()) { using (HttpClient httpClient = GetHttpClient(handler)) { using (StringContent content = new StringContent(json, Encoding.UTF8, "application/json")) { Uri uri = new Uri(UrlManager.LoginUrl); using (HttpResponseMessage responseMessage = await httpClient.PostAsync(uri, content, cancellationToken)) { string responseJson = await responseMessage.Content.ReadAsStringAsync(); AuthResponseModel response = JsonConvert.DeserializeObject <AuthResponseModel>(responseJson); if (response.Success) { Session = new Session { Username = response.User.Name, Cookies = handler.CookieContainer .GetCookies(new Uri(UrlManager.BaseHttpAdress)) .Cast <Cookie>().ToDictionary(c => c.Name, c => c.Value) }; } else { if (response.Errors != null && response.Errors.Count > 0) { throw new Exception(response.Errors.First()); } else { throw new Exception($"Server responded with code {(int)responseMessage.StatusCode} {responseMessage.StatusCode} while logging in"); } } } } } } }
public ActionResult <AuthResponseModel> Login([FromBody] AuthRequestModel authRequestModel) { if (ModelState.IsValid) { var token = AuthenticationHandler.Authenticate(authRequestModel.Username, authRequestModel.Password); var authResponseModel = new AuthResponseModel() { token = token }; return(Ok(authResponseModel)); } else { return(BadRequest()); } }
public async Task <AuthResponseModel> UserRegisterAsync(string username, string email, string password) { string myJason = "{'UserName': '******', 'Email': '" + email + "', 'Pass': '******'}"; JsonData json = new JsonData(); var response = new AuthResponseModel(); try { using (var client = new HttpClient()) { var post = await client.PostAsync( "http://localhost:20000/api/register", new StringContent(myJason, System.Text.Encoding.UTF8, "application/json")); json = await post.Content.ReadAsStringAsync(); json.ToString(); } json = JsonMapper.ToObject(json.ToString()); response.Response = (int)json["response"]; response.Status = json["status"].ToString(); response.Info = json["info"].ToString(); } catch (Exception e) { using (var client = new HttpClient()) { var post = await client.PostAsync( "http://localhost:20000/api/register", new StringContent(myJason, System.Text.Encoding.UTF8, "application/json")); json = await post.Content.ReadAsStringAsync(); json.ToString(); } json = JsonMapper.ToObject(json.ToString()); response.Response = (int)json["response"]; response.Status = json["status"].ToString(); response.Info = json["info"].ToString(); } return(response); }
public AuthResponseModel GetUserClaims() { var identityClaims = User.Identity as ClaimsIdentity; AuthResponseModel authResponse = new AuthResponseModel { Authorized = identityClaims.FindFirst("Authorized")?.Value, Message = identityClaims.FindFirst("Message")?.Value, UserDisplayName = identityClaims.FindFirst("UserDisplayName")?.Value, LoggedOn = identityClaims.FindFirst("LoggedOn")?.Value, Admin = identityClaims.FindFirst("Admin")?.Value, IT = identityClaims.FindFirst("IT")?.Value, Application = identityClaims.FindFirst("Application")?.Value, UserEmailAddress = identityClaims.FindFirst("UserEmailAddress")?.Value, }; return(authResponse); }