public async Task <IActionResult> PutDriver([FromRoute] int id, [FromBody] Driver record) { if (await repo.CheckDefaultDriverExists(id, record) != null) { return(StatusCode(409, new { response = ApiMessages.DefaultDriverAlreadyExists() })); } ; if (id == record.Id && ModelState.IsValid) { try { repo.Update(record); return(StatusCode(200, new { response = ApiMessages.RecordUpdated() })); } catch (DbUpdateException exception) { LoggerExtensions.LogException(0, logger, ControllerContext, record, exception); return(StatusCode(490, new { response = ApiMessages.RecordNotSaved() })); } } LoggerExtensions.LogException(0, logger, ControllerContext, record, null); return(StatusCode(400, new { response = ApiMessages.InvalidModel() })); }
private async Task <IActionResult> GenerateNewToken(TokenRequest model) { var user = await userManager.FindByNameAsync(model.Username); if (user != null && await userManager.CheckPasswordAsync(user, model.Password)) { if (!await userManager.IsEmailConfirmedAsync(user)) { return(BadRequest(new { response = ApiMessages.AccountNotConfirmed() })); } var newRefreshToken = CreateRefreshToken(appSettings.ClientId, user.Id); var oldRefreshTokens = db.Tokens.Where(rt => rt.UserId == user.Id); if (oldRefreshTokens != null) { foreach (var token in oldRefreshTokens) { db.Tokens.Remove(token); } } db.Tokens.Add(newRefreshToken); await db.SaveChangesAsync(); var accessToken = await CreateAccessToken(user, newRefreshToken.Value); return(Ok(new { response = accessToken })); } return(Unauthorized(new { response = ApiMessages.AuthenticationFailed() })); }
private static void LogInvalidModel(Object record, ILogger logger, ControllerContext context) { logger.LogError("{caller} {error} {record}", GetControllerAndActionName(context), GetSimpleDescription(ApiMessages.InvalidModel()), GetObjectProperties(record)); }
public async Task <IActionResult> Register([FromBody] RegisterViewModel formData) { if (ModelState.IsValid) { var user = new AppUser { Email = formData.Email, DisplayName = formData.Displayname, UserName = formData.Username, IsAdmin = formData.IsAdmin, EmailConfirmed = true, IsFirstLogin = true, OneTimePassword = formData.Password, IsOneTimePasswordChanged = false, SecurityStamp = Guid.NewGuid().ToString() }; var result = await userManager.CreateAsync(user, formData.Password); if (result.Succeeded) { await userManager.AddToRoleAsync(user, user.IsAdmin? "Admin" : "User"); return(StatusCode(200, new { response = ApiMessages.RecordCreated() })); } else { return(StatusCode(492, new { response = result.Errors.Select(x => x.Description) })); } } return(StatusCode(400, new { response = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage) })); }
private async Task <IActionResult> RefreshToken(TokenRequest model) { try { var rt = db.Tokens.FirstOrDefault(t => t.ClientId == appSettings.ClientId && t.Value == model.RefreshToken.ToString()); if (rt == null) { return(new UnauthorizedResult()); } if (rt.ExpiryTime < DateTime.UtcNow) { return(Unauthorized(new { response = ApiMessages.AuthenticationFailed() })); } var user = await userManager.FindByIdAsync(rt.UserId); if (user == null) { return(Unauthorized(new { response = ApiMessages.AuthenticationFailed() })); } var rtNew = CreateRefreshToken(rt.ClientId, rt.UserId); db.Tokens.Remove(rt); db.Tokens.Add(rtNew); db.SaveChanges(); var token = await CreateAccessToken(user, rtNew.Value); return(Ok(new { response = token })); } catch { return(Unauthorized(new { response = ApiMessages.AuthenticationFailed() })); } }
public IActionResult AssignDriver(int driverId, [FromQuery(Name = "id")] int[] ids) { try { repo.AssignDriver(driverId, ids); return(StatusCode(200, new { response = ApiMessages.RecordUpdated() })); } catch (DbUpdateException exception) { LoggerExtensions.LogException(driverId, logger, ControllerContext, null, exception); return(StatusCode(490, new { response = ApiMessages.RecordNotSaved() })); } }
public IActionResult SendFirstLoginCredentials([FromBody] FirstLoginCredentialsViewModel model) { string baseUrl = $"{Request.Scheme}://{Request.Host.Value}{Request.PathBase.Value}"; string loginLink = Url.Content($"{baseUrl}/login"); var result = emailSender.SendFirstLoginCredentials(model, loginLink); if (result.Successful) { return(StatusCode(200, new { response = ApiMessages.EmailInstructions() })); } return(StatusCode(496, new { response = ApiMessages.EmailNotSent() })); }
public async Task <IActionResult> GetDefaultDriver() { Driver record = await repo.GetDefaultDriver(); if (record == null) { LoggerExtensions.LogException(0, logger, ControllerContext, null, null); return(StatusCode(404, new { response = ApiMessages.DefaultDriverNotFound() })); } return(StatusCode(200, record)); }
public async Task <IActionResult> GetPickupPoint(int id) { PickupPoint record = await repo.GetById(id); if (record == null) { LoggerExtensions.LogException(id, logger, ControllerContext, null, null); return(StatusCode(404, new { response = ApiMessages.RecordNotFound() })); } return(StatusCode(200, record)); }
public async Task <IActionResult> Auth([FromBody] TokenRequest model) { switch (model.GrantType) { case "password": return(await GenerateNewToken(model)); case "refresh_token": return(await RefreshToken(model)); default: return(Unauthorized(new { response = ApiMessages.AuthenticationFailed() })); } }
public async Task <IActionResult> PatchPickupPoint(int pickupPointId, [FromQuery(Name = "coordinates")] string coordinates) { PickupPoint record = await repo.GetById(pickupPointId); try { repo.UpdateCoordinates(pickupPointId, coordinates); return(StatusCode(200, new { response = ApiMessages.RecordUpdated() })); } catch (DbUpdateException exception) { LoggerExtensions.LogException(pickupPointId, logger, ControllerContext, null, exception); return(StatusCode(490, new { response = ApiMessages.RecordNotSaved() })); } }
public async Task <IActionResult> GetTransfer(int id) { var transfer = await repo.GetById(id); if (transfer == null) { LoggerExtensions.LogException(id, logger, ControllerContext, null, null); return(StatusCode(404, new { response = ApiMessages.RecordNotFound() })); } ; return(StatusCode(200, transfer)); }
public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await userManager.FindByEmailAsync(model.Email); if (user != null && await userManager.IsEmailConfirmedAsync(user)) { string token = await userManager.GeneratePasswordResetTokenAsync(user); string tokenEncoded = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token)); string baseUrl = $"{Request.Scheme}://{Request.Host.Value}{Request.PathBase.Value}"; string passwordResetLink = Url.Content($"{baseUrl}/account/resetPassword?email={model.Email}&token={tokenEncoded}"); emailSender.SendResetPasswordEmail(user.DisplayName, user.Email, passwordResetLink, model.Language); return(StatusCode(200, new { response = ApiMessages.EmailInstructions() })); } return(StatusCode(200, new { response = ApiMessages.EmailInstructions() })); } return(StatusCode(400, new { response = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage) })); }
public IActionResult PutPickupPoint([FromRoute] int id, [FromBody] PickupPoint record) { if (id == record.Id && ModelState.IsValid) { try { repo.Update(record); return(StatusCode(200, new { response = ApiMessages.RecordUpdated() })); } catch (DbUpdateException exception) { LoggerExtensions.LogException(0, logger, ControllerContext, record, exception); return(StatusCode(490, new { response = ApiMessages.RecordNotSaved() })); } } LoggerExtensions.LogException(0, logger, ControllerContext, record, null); return(StatusCode(400, new { response = ApiMessages.InvalidModel() })); }
public IActionResult PostPort([FromBody] Port record) { if (ModelState.IsValid) { try { repo.Create(record); return(StatusCode(200, new { response = ApiMessages.RecordCreated() })); } catch (Exception exception) { LoggerExtensions.LogException(0, logger, ControllerContext, record, exception); return(StatusCode(490, new { response = ApiMessages.RecordNotSaved() })); } } LoggerExtensions.LogException(0, logger, ControllerContext, record, null); return(StatusCode(400, new { response = ApiMessages.InvalidModel() })); }
private async Task <IActionResult> GenerateNewToken(TokenRequest model) { var user = await userManager.FindByNameAsync(model.Username); if (user != null && user.IsActive && await userManager.CheckPasswordAsync(user, model.Password)) { if (this.IsFirstLogin(user)) { await this.UpdateFirstLogin(user); } else { if (IsOneTimePasswordChanged(user) == false) { return(StatusCode(401, new { response = ApiMessages.AuthenticationFailed() })); } } if (!await userManager.IsEmailConfirmedAsync(user)) { return(StatusCode(495, new { response = ApiMessages.AccountNotConfirmed() })); } var newRefreshToken = CreateRefreshToken(settings.ClientId, user.Id); var oldRefreshTokens = db.Tokens.Where(rt => rt.UserId == user.Id); if (oldRefreshTokens != null) { foreach (var token in oldRefreshTokens) { db.Tokens.Remove(token); } } db.Tokens.Add(newRefreshToken); await db.SaveChangesAsync(); var accessToken = await CreateAccessToken(user, newRefreshToken.Value); return(StatusCode(200, new { response = accessToken })); } return(StatusCode(401, new { response = ApiMessages.AuthenticationFailed() })); }
public IActionResult PostTransfer([FromBody] SaveTransferResource record) { if (ModelState.IsValid) { try { repo.Create(mapper.Map <SaveTransferResource, Transfer>(record)); SendNotificationsToClients(); return(StatusCode(200, new { response = ApiMessages.RecordCreated() })); } catch (Exception exception) { LoggerExtensions.LogException(0, logger, ControllerContext, record, exception); return(StatusCode(490, new { response = ApiMessages.RecordNotSaved() })); } } LoggerExtensions.LogException(0, logger, ControllerContext, record, null); return(StatusCode(400, new { response = ApiMessages.InvalidModel() })); }
public async Task <IActionResult> GetUser(string id) { AppUser record = await userManager.FindByIdAsync(id); if (record == null) { LoggerExtensions.LogException(id, logger, ControllerContext, null, null); return(StatusCode(404, new { response = ApiMessages.RecordNotFound() })); } UserViewModel vm = new UserViewModel { Id = record.Id, UserName = record.UserName, DisplayName = record.DisplayName, Email = record.Email, IsAdmin = record.IsAdmin, IsActive = record.IsActive, OneTimePassword = record.OneTimePassword }; return(StatusCode(200, vm)); }
public async Task <IActionResult> PutUser([FromRoute] string id, [FromBody] UserViewModel vm) { if (id == vm.Id && ModelState.IsValid) { AppUser record = await userManager.FindByIdAsync(id); if (record != null) { await UpdateUser(record, vm); await UpdateRole(record); return(StatusCode(200, new { response = ApiMessages.RecordUpdated() })); } LoggerExtensions.LogException(id, logger, ControllerContext, null, null); return(StatusCode(404, new { response = ApiMessages.RecordNotFound() })); } LoggerExtensions.LogException(0, logger, ControllerContext, vm, null); return(StatusCode(400, new { response = ApiMessages.InvalidModel() })); }
public async Task <IActionResult> DeleteDriver([FromRoute] int id) { Driver record = await repo.GetById(id); if (record == null) { LoggerExtensions.LogException(id, logger, ControllerContext, null, null); return(StatusCode(404, new { response = ApiMessages.RecordNotFound() })); } try { repo.Delete(record); return(StatusCode(200, new { response = ApiMessages.RecordDeleted() })); } catch (DbUpdateException exception) { LoggerExtensions.LogException(0, logger, ControllerContext, record, exception); return(StatusCode(491, new { response = ApiMessages.RecordInUse() })); } }
public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordViewModel model) { if (ModelState.IsValid) { var user = await userManager.FindByEmailAsync(model.Email); if (user != null) { var result = await userManager.ResetPasswordAsync(user, Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(model.Token)), model.Password); if (result.Succeeded) { await signInManager.RefreshSignInAsync(user); await this.UpdateIsOneTimePasswordChanged(user); return(StatusCode(200, new { response = ApiMessages.PasswordReset() })); } return(StatusCode(494, new { response = result.Errors.Select(x => x.Description) })); } return(StatusCode(404, new { response = ApiMessages.RecordNotFound() })); } return(StatusCode(400, new { response = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage) })); }
public async Task <IActionResult> DeleteUser(string id) { AppUser record = await userManager.FindByIdAsync(id); if (record == null) { LoggerExtensions.LogException(id, logger, ControllerContext, null, null); return(StatusCode(404, new { response = ApiMessages.RecordNotFound() })); } try { IdentityResult result = await userManager.DeleteAsync(record); return(StatusCode(200, new { response = ApiMessages.RecordDeleted() })); } catch (DbUpdateException exception) { LoggerExtensions.LogException(0, logger, ControllerContext, record, exception); return(StatusCode(491, new { response = ApiMessages.RecordInUse() })); } }
public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordViewModel vm) { if (ModelState.IsValid) { var user = await userManager.FindByIdAsync(vm.UserId); if (user != null) { var result = await userManager.ChangePasswordAsync(user, vm.CurrentPassword, vm.Password); if (result.Succeeded) { await signInManager.RefreshSignInAsync(user); await this.UpdateIsOneTimePasswordChanged(user); return(StatusCode(200, new { response = ApiMessages.PasswordChanged() })); } return(StatusCode(494, new { response = result.Errors.Select(x => x.Description) })); } return(StatusCode(404, new { response = ApiMessages.RecordNotFound() })); } return(StatusCode(400, new { response = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage) })); }