public virtual async Task <IAPIResultVM> AddAsync(A model, Guid?userId = null, bool isCommit = true) { try { Guid _userId = userId == null ? Guid.Empty : userId.Value; D entity = _mapper.Map <A, D>(model); if (entity.Id == null || entity.Id == Guid.Empty) { entity.Id = Guid.NewGuid(); } if (entity is ITableEntity) { (entity as ITableEntity).CreateBy = _userId; (entity as ITableEntity).CreateDT = DateTime.UtcNow; } Repository.Add(entity); if (isCommit) { await CommitAsync(); } return(_apiResult.CreateVMWithRec(entity, entity.Id, true)); } catch (Exception e) { SentrySdk.CaptureException(e); return(_apiResult.CreateVM()); } }
public virtual async Task <APIResultVM> ReverseDelete(Guid id, Guid?userId, bool isCommit = true) { try { Guid _userId = userId == null ? Guid.Empty : userId.Value; D entity = await uow.Repository <D>().GetByID(id); if (Validation.IsNull(entity)) { return(APIResult.CreateVM(false, id, AppStatusCode.WRG01001)); } if (entity is ITable) { (entity as ITable).UpdateBy = _userId; (entity as ITable).UpdateDT = DateTime.Now; } entity.IsDeleted = false; Repository.Update(entity); if (isCommit) { await Commit(); } return(APIResult.CreateVMWithRec(entity, true, entity.Id)); } catch (Exception e) { return(APIResult.CreateVMWithError(e)); } }
public virtual async Task <APIResultVM> Add(A model, Guid?userId = null, bool isCommit = true) { try { Guid _userId = userId == null ? Guid.Empty : userId.Value; D entity = mapper.Map <A, D>(model); if (entity.Id == null || entity.Id == Guid.Empty) { entity.Id = Guid.NewGuid(); } if (entity is ITable) { (entity as ITable).CreateBy = _userId; (entity as ITable).CreateDT = DateTime.Now; } Repository.Add(entity); if (isCommit) { await Commit(); } return(APIResult.CreateVMWithRec(entity, true, entity.Id)); } catch (Exception e) { return(APIResult.CreateVMWithError(e)); } }
public async Task <JsonResult> Register(UserAddVM model) { try { if (ModelState.IsValid) { User entity = _mapper.Map <UserAddVM, User>(model); entity.Id = Guid.NewGuid(); entity.CreateDateTime = DateTime.UtcNow; entity.LastLoginDateTime = DateTime.UtcNow; var identityResult = await _userManager.CreateAsync(entity, model.PasswordHash); if (identityResult.Succeeded) { await _signInManager.SignInAsync(entity, isPersistent : false); UserAuthenticateVM returnVM = new UserAuthenticateVM(); returnVM = _mapper.Map <User, UserAuthenticateVM>(entity); returnVM.Token = GetToken(entity); return(new JsonResult(returnVM)); } else { return(new JsonResult(APIResult.CreateVMWithRec <object>(identityResult.Errors))); } } } catch (Exception ex) { return(new JsonResult(APIResult.CreateVMWithError(ex, APIResult.CreateVM(false, null, AppStatusCode.ERR01001)))); } return(new JsonResult(APIResult.CreateVM(false, null, AppStatusCode.ERR01001))); }
public async Task <JsonResult> RefreshToken() { var user = await _userManager.FindByNameAsync( User.Identity.Name ?? User.Claims.Where(c => c.Properties.ContainsKey("unique_name")).Select(c => c.Value).FirstOrDefault() ); return(new JsonResult(APIResult.CreateVMWithRec <string>(GetToken(user), true))); }
public async Task <JsonResult> Register([FromBody] UserRegisterVM model) { if (!ModelState.IsValid) { return(new JsonAPIResult(_apiResult.CreateVMWithModelState(modelStateDictionary: ModelState), StatusCodes.Status400BadRequest)); } User entity = _mapper.Map <UserRegisterVM, User>(model); entity.Id = Guid.NewGuid(); entity.CreateDateTime = DateTime.UtcNow; var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, entity.Id.ToString()), new Claim(JwtRegisteredClaimNames.UniqueName, entity.UserName), new Claim("UserId", entity.Id.ToString()) }; TokenCacheVM authData = new TokenCacheVM(); authData.AccessToken = _tokenService.GenerateAccessToken(claims); authData.RefreshToken = _tokenService.GenerateRefreshToken(); authData.AccessTokenExpiryTime = new JwtSecurityTokenHandler().ReadToken(authData.AccessToken)?.ValidTo ?? DateTime.MinValue; authData.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(1); authData.Id = entity.Id; var identityResult = await _userManager.CreateAsync(entity, model.Password); if (!identityResult.Succeeded) { return(new JsonAPIResult(_apiResult.CreateVMWithIdentityErrors(errors: identityResult.Errors), StatusCodes.Status422UnprocessableEntity)); } TimeSpan expiryTimeSpan = TimeSpan.FromSeconds(_tokenService.GetTokenExpiryDuration()); var cacheResult = _tokenService.Redis.Insert(authData, expiryTimeSpan); if (!cacheResult.IsSuccessful) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01011), StatusCodes.Status409Conflict)); } await _signInManager.SignInAsync(entity, isPersistent : false); UserAuthenticationVM returnVM = new UserAuthenticationVM(); returnVM = _mapper.Map <User, UserAuthenticationVM>(entity); returnVM.TokenData = authData; return(new JsonAPIResult(_apiResult.CreateVMWithRec <UserAuthenticationVM>(returnVM, entity.Id, true), StatusCodes.Status201Created)); }
public virtual async Task <APIResultVM> DeleteAsync(Guid id, Guid?userId = null, bool shouldBeOwner = false, bool isCommit = true) { try { Guid _userId = userId == null ? Guid.Empty : userId.Value; D entity = await _uow.Repository <D>(_repositoryLogger).GetByIDAysnc(id); if (entity.IsNull()) { return(APIResult.CreateVM(false, id, new List <string>() { ErrorMessages.RecordNotFound })); } if (shouldBeOwner && (_userId == Guid.Empty || _userId != (entity as ITableEntity).CreateBy)) { return(APIResult.CreateVM(false, id, new List <string>() { ErrorMessages.NotOwnerOfRecord })); } if (entity is ITableEntity) { (entity as ITableEntity).UpdateBy = _userId; (entity as ITableEntity).UpdateDT = DateTime.Now; } entity.IsDeleted = true; Repository.Update(entity); if (isCommit) { await CommitAsync(); } return(APIResult.CreateVMWithRec(entity, true, entity.Id)); } catch (Exception e) { _logger.LogError("BaseService.DeleteAsync", e); return(APIResult.CreateVM(messages: new List <string>() { "An exception occured!" })); } }
public virtual async Task <JsonResult> Get(Guid id) { if (Validation.IsNullOrEmpty(id)) { return(new JsonResult(APIResult.CreateVM(false, null, AppStatusCode.WRG01002))); } var result = await _service.GetByID(id); if (result == null) { return(new JsonResult(APIResult.CreateVM(false, null, AppStatusCode.WRG01001))); } return(new JsonResult(APIResult.CreateVMWithRec <G>(result, true, result.Id))); }
public async Task <APIResultVM> GetProfileData(Guid userId, Guid currentUserId, string sortOrder = "", int pageNumber = 1, int pageItemCount = 10, Guid?categoryId = null) { if (userId == null || userId == Guid.Empty) { APIResult.CreateVM(); } var user = _con.Set <User>().AsNoTracking().Where(a => a.Id == userId).FirstOrDefault(); if (user == null) { APIResult.CreateVM(); } ProfileVM model = new ProfileVM(); _mapper.Map <ProfileVM>(user); model.Suggestion = new SuggestionPaggingListVM(); model.Suggestion.Pagging = new PaggingVM(); model.Suggestion.Records = _suggestionService.GetAllAsync(a => a.CreateBy == userId, true, sortOrder, pageNumber, pageItemCount, categoryId).Result; model.Comments = await _suggestionCommentService.GetCommentsOfUser(userId); model.Reactions = await _suggestionReactionService.GetReactionsOfUser(userId); model.UserId = userId; model.PictureUrl = user.PictureUrl; model.CurrentUserId = currentUserId; model.EMail = user.Email; model.SuggetionCount = _con.Set <Suggestion>().Where(a => !a.IsDeleted && a.CreateBy == userId).Count(); model.Suggestion.Pagging.ActionName = "Profile"; model.Suggestion.Pagging.ControllerName = "User"; var query = _con.Set <Suggestion>().Where(a => !a.IsDeleted && a.CreateBy == userId).AsNoTracking().AsQueryable(); model.Suggestion.Pagging.IsNextPageExist = query.Skip((pageNumber * pageItemCount)).Take(1).Count() == 1; foreach (var item in model.Suggestion.Records) { item.CreateByName = user.Email; } return(APIResult.CreateVMWithRec <ProfileVM>(model, true, userId)); }
public JsonResult GetById([FromRoute] Guid id) { if (id.IsEmptyGuid()) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01003), StatusCodes.Status400BadRequest)); } var user = _service.GetById(id); if (user == null) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01002), StatusCodes.Status404NotFound)); } var result = _mapper.Map <UserVM>(user); return(new JsonAPIResult(_apiResult.CreateVMWithRec <UserVM>(result, result.Id, true), StatusCodes.Status200OK)); }
public IAPIResultVM <TKey> Insert(TEntity entity, TimeSpan?expiryTime = null) { try { if (entity.Id.IsNull()) { assignEntityId(ref entity); } var keyStr = System.Convert.ToString(entity.Id); string json = JsonSerializer.Serialize(entity); bool isSuccessful = _database.StringSet(keyStr, json, expiryTime); return(_apiResult.CreateVMWithRec <TEntity>(entity, entity.Id, isSuccessful)); } catch (Exception e) { SentrySdk.CaptureException(e); return(_apiResult.CreateVM(entity.Id)); } }
public virtual async Task <APIResultVM> Update(Guid id, U model, Guid?userId = null, bool isCommit = true) { try { Guid _userId = userId == null ? Guid.Empty : userId.Value; if (model.Id == null || model.Id == Guid.Empty) { model.Id = Guid.NewGuid(); } D entity = await uow.Repository <D>().GetByID(model.Id); if (Validation.IsNull(entity)) { APIResult.CreateVM(false, id, AppStatusCode.WRG01001); } entity = mapper.Map <U, D>(model, entity); if (entity is ITable) { (entity as ITable).UpdateBy = _userId; (entity as ITable).UpdateDT = DateTime.Now; } uow.Repository <D>().Update(entity); if (isCommit) { await Commit(); } return(APIResult.CreateVMWithRec(entity, true, entity.Id)); } catch (Exception e) { throw e; } }
public JsonResult GetById(Guid id) { try { if (Validation.IsNullOrEmpty(id)) { return(new JsonResult(APIResult.CreateVM(false, null, AppStatusCode.WRG01002))); } var result = _service.GetById(id); if (result == null) { return(new JsonResult(APIResult.CreateVM(false, null, AppStatusCode.WRG01001))); } return(new JsonResult(APIResult.CreateVMWithRec <User>(result, true, result.Id))); } catch (Exception ex) { return(new JsonResult(APIResult.CreateVMWithError(ex, APIResult.CreateVM(false, null, AppStatusCode.ERR01001)))); } }
public virtual async Task <APIResultVM> AddAsync(S model, Guid?userId = null, bool isCommit = true) { try { Guid _userId = userId == null ? Guid.Empty : userId.Value; D entity = _mapper.Map <S, D>(model); if (entity.Id == null || entity.Id == Guid.Empty) { entity.Id = Guid.NewGuid(); } if (entity is ITableEntity) { (entity as ITableEntity).CreateBy = _userId; (entity as ITableEntity).CreateDT = DateTime.Now; } Repository.Add(entity); if (isCommit) { await CommitAsync(); } return(APIResult.CreateVMWithRec(entity, true, entity.Id)); } catch (Exception e) { _logger.LogError("BaseService.AddAsync", e); return(APIResult.CreateVM(messages: new List <string>() { "An exception occured!" })); } }
public JsonResult Refresh([FromBody] TokenRefreshVM model) { try { if (!ModelState.IsValid) { return(new JsonAPIResult(_apiResult.CreateVMWithModelState(modelStateDictionary: ModelState), StatusCodes.Status400BadRequest)); } var principal = _tokenService.GetPrincipalFromExpiredToken(model.AccessToken); if (!principal.Claims.Any()) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(statusCode: APIStatusCode.ERR02026), StatusCodes.Status400BadRequest)); } Guid userId = Guid.Empty; var userIdClaim = principal.Claims.FirstOrDefault(o => o.Type == "UserId"); if (userIdClaim != null && Guid.TryParse(userIdClaim.Value, out userId) && userId.IsEmptyGuid()) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(statusCode: APIStatusCode.ERR01004), StatusCodes.Status404NotFound)); } var authData = _tokenService.Redis.GetById(userId); if (authData.IsNull() || authData.Id.IsEmptyGuid()) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(statusCode: APIStatusCode.ERR02023), StatusCodes.Status400BadRequest)); } else if (!authData.AccessToken.IsNullOrEmptyString() && authData.AccessTokenExpiryTime > DateTime.UtcNow) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(statusCode: APIStatusCode.ERR02025), StatusCodes.Status400BadRequest)); } if (authData.RefreshToken != model.RefreshToken) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(statusCode: APIStatusCode.ERR02024), StatusCodes.Status400BadRequest)); } if (authData.RefreshTokenExpiryTime <= DateTime.UtcNow) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(statusCode: APIStatusCode.ERR02023), StatusCodes.Status400BadRequest)); } List <Claim> newClaims = new List <Claim>() { new Claim("UserId", userId.ToString()) }; authData.AccessToken = _tokenService.GenerateAccessToken(newClaims); authData.RefreshToken = _tokenService.GenerateRefreshToken(); TimeSpan expiryTimeSpan = TimeSpan.FromSeconds(_tokenService.GetTokenExpiryDuration()); var updateResult = _tokenService.Redis.Insert(authData, expiryTimeSpan); if (!updateResult.IsSuccessful) { return(new JsonAPIResult(_apiResult.CreateVMWithStatusCode(null, false, APIStatusCode.ERR01011), StatusCodes.Status409Conflict)); } return(new JsonAPIResult(_apiResult.CreateVMWithRec <TokenRefreshVM>(new TokenRefreshVM() { AccessToken = authData.AccessToken, RefreshToken = authData.RefreshToken }, null, true), StatusCodes.Status200OK)); } catch (SecurityTokenException stEx) { SentrySdk.CaptureException(stEx); return(new JsonAPIResult("", StatusCodes.Status500InternalServerError)); } catch (Exception ex) { SentrySdk.CaptureException(ex); return(new JsonAPIResult("", StatusCodes.Status500InternalServerError)); } }