public async Task <JsonResult> Add([FromBody] WorktaskUpdateModel model) { var worktask = model.worktask; int projectId = worktask.ProjectId; int userId = int.Parse(User.Identity.Name); // Проверяем доступ var linkedProject = await _context.GetLinkedAcceptedProject(projectId, userId) .ConfigureAwait(false); if (linkedProject == null) { throw new Exception(TextResource.API_NoAccess); } worktask.CreatedDate = DateTime.UtcNow; var addedTask = await _context.AddAsync(worktask) .ConfigureAwait(false); await _context.SaveChangesAsync(true) .ConfigureAwait(false); return(new JsonResult(new WorktaskAddResponse { worktask = worktask })); }
public async Task <JsonResult> Add([FromBody] AddProjectModel model) { if (model.title.Length < 5 || model.title.Length > 50) { throw new Exception("Неверная длина названия проекта"); } if (model.description.Length > 250) { throw new Exception("Неверная длина описания проекта"); } int userId = int.Parse(User.Identity.Name); var addedProject = await _dbContext.AddAsync(new Project { Title = model.title, Description = model.description }) .ConfigureAwait(false); await _dbContext.SaveChangesAsync(true) .ConfigureAwait(false); await _dbContext.AddAsync(new LinkedProject { Accepted = true, ProjectId = addedProject.Entity.Id, RoleId = 3, UserId = userId }) .ConfigureAwait(false); await _dbContext.SaveChangesAsync(true) .ConfigureAwait(false); return(new JsonResult(new ProjectUpdateResponse { project = addedProject.Entity })); }
public async Task <JsonResult> SignUp([FromBody] SignUpModel model) { var dbUser = await _dbContext.Users.FirstOrDefaultAsync(x => x.Login == model.Login) .ConfigureAwait(false); if (dbUser != null) { throw new Exception("Пользователь с таким логином уже существует"); } // Хешируем пароли var salt = PasswordHelpers.GenerateSalt(); var hash = PasswordHelpers.EncryptPassword(model.Pass, salt); // Шифруем личные данные var IV = PasswordHelpers.GetIV(); var firstName = PasswordHelpers.EncryptData(model.FirstName, IV); var surName = PasswordHelpers.EncryptData(model.Surname, IV); var email = PasswordHelpers.EncryptData(model.Email, IV); var middleName = string.IsNullOrEmpty(model.MiddleName) ? null : PasswordHelpers.EncryptData(model.MiddleName, IV); var birthdate = string.IsNullOrEmpty(model.BirthDate) ? null : PasswordHelpers.EncryptData(model.BirthDate, IV); var city = string.IsNullOrEmpty(model.City) ? null : PasswordHelpers.EncryptData(model.City, IV); var user = new User { Login = model.Login, Pass = new Pass { Password = hash, Salt = salt }, IV = IV, FirstName = firstName, Surname = surName, MiddleName = middleName, City = city, BirthDate = birthdate, Email = email }; await _dbContext.AddAsync(user) .ConfigureAwait(false); await _dbContext.SaveChangesAsync(true) .ConfigureAwait(false); return(new JsonResult(new OkResponse { message = "Регистрация пройдена успешно" })); }
public static async Task GenerateToken(string id, Token user, TimetrackerContext context, bool isNew = false) { var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, id) }; var claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); var now = DateTime.UtcNow; var expiredIn = now.Add(tokenDurability); var jwt = new JwtSecurityToken( issuer: TimetrackerAuthorizationOptions.ISSUER, audience: TimetrackerAuthorizationOptions.AUDIENCE, notBefore: now, claims: claimsIdentity.Claims, expires: expiredIn, signingCredentials: new SigningCredentials( TimetrackerAuthorizationOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256) ); var access_token = new JwtSecurityTokenHandler().WriteToken(jwt); var refresh_token = Guid.NewGuid().ToString().Replace("-", ""); user.AccessToken = access_token; user.RefreshToken = refresh_token; user.TokenExpiredDate = expiredIn; if (isNew) { await context.AddAsync(user) .ConfigureAwait(false); } await context.SaveChangesAsync(true) .ConfigureAwait(false); }
public async Task StartTracking(int?taskId) { var worktaskId = taskId.Value; var userName = Context.User.Identity.Name; int userId = int.Parse(Context.User.Identity.Name); var anyActiveWorktrack = await _dbContext.Worktracks.AsNoTracking() .AnyAsync(x => x.User.Id == userId && x.Running) .ConfigureAwait(false); if (anyActiveWorktrack) { await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "У вас уже есть задача, которая отслеживается.") .ConfigureAwait(false); return; } var worktaskData = await _dbContext.Worktasks.AsNoTracking() .Where(x => x.Id == worktaskId) .Select(x => new { x.ProjectId, x.State }) .FirstOrDefaultAsync() .ConfigureAwait(false); if (worktaskData == null) { await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "Не существует задачи с таким идентификатором") .ConfigureAwait(false); return; } var projectId = worktaskData.ProjectId; if (_dbContext.GetLinkedAcceptedProject(projectId, userId) == null) { await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "У вас недостаточно прав, чтобы отслеживать эту задачу.") .ConfigureAwait(false); return; } if (worktaskData.State.Id == 6) { await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "Данная задача уже закрыта") .ConfigureAwait(false); return; } var now = DateTime.UtcNow; var worktrack = await _dbContext.AddAsync(new Worktrack { UserId = userId, StartedTime = now, StoppedTime = now, WorktaskId = worktaskId, Running = true }) .ConfigureAwait(false); await _dbContext.SaveChangesAsync() .ConfigureAwait(false); var group = Clients.Group(userName); await group.SendAsync("getActiveTracking", true, worktrack.Entity, true, string.Empty) .ConfigureAwait(false); }