public async Task <ActionResult <MainResponse> > TokenRefresh() { User user = HttpContext.GetUser(); if (user == null) { return(MainResponse.GetError(Enums.RequestError.UserNotFound)); } if (!HttpContext.Request.Cookies.Any(p => p.Key == "refresh-token")) { return(Forbid()); } Auth auth = _context.Auth.FirstOrDefault(p => p.RefreshToken == HttpContext.Request.Cookies["refresh-token"]); if (auth == null) { return(Forbid()); } auth.Token = RandomUtilities.GetCryptoRandomString(32); auth.RefreshToken = RandomUtilities.GetCryptoRandomString(32); auth.Expire = DateTime.Now.AddSeconds(_serverConfig.Users.TokenExpirationTime); _context.Auth.Update(auth); await _context.SaveChangesAsync(); HttpContext.Response.Cookies.Append("refresh-token", auth.RefreshToken, new CookieOptions() { Domain = coockieDomain, HttpOnly = true, Path = "/api/auth/token-refresh" }); HttpContext.Response.Cookies.Append("auth-token", auth.Token, new CookieOptions() { Domain = coockieDomain, HttpOnly = true, Path = "/api" }); HttpContext.Response.Cookies.Append("auth-token", auth.Token, new CookieOptions() { Domain = coockieDomain, HttpOnly = true, Path = "/sockets" }); TokenRefreshResponse response = new TokenRefreshResponse() { EncryptionKey = auth.LocalDataEncryptionKey }; return(MainResponse.GetSuccess(response)); }
public async Task <ActionResult <MainResponse> > CreateChat(CreateChatRequest request) { User user = HttpContext.GetUser(); if (user == null || user.KeySession == null) { return(Unauthorized()); } int[] keyIds = request.EncryptedPayload.Select(p => p.KeyId).ToArray(); Chat chat = new Chat() { Id = RandomUtilities.GetCryptoRandomString(20), EncryptionChatDatas = new List <EncryptionChatData>(), Image = "", LastMessageDate = DateTime.Now, LastMessageId = null, Messages = new List <Message>(), }; _context.Chats.Add(chat); await _context.SaveChangesAsync(); User[] users = await _context.Users.Where(p => keyIds.Contains(p.RSAKeyPair.Id)).ToArrayAsync(); EncryptionChatData[] encryptionChatDatas = new EncryptionChatData[users.Length + 1]; CreateChatEncryptedPayload encryptedPayload; for (int i = 0; i < users.Length; i++) { encryptedPayload = request.EncryptedPayload.First(p => p.KeyId == users[i].RSAKeyPair.Id); encryptionChatDatas[i] = new EncryptionChatData() { AESEncryptedKey = new AESEncryptedData(), Chat = chat, EncryptedTitle = new AESEncryptedData(), KeyTransferPayload = encryptedPayload.PayLoad, RSAEncryptedKey = encryptedPayload.EncryptedChatKey, RSAKeyPair = users[i].RSAKeyPair }; } encryptionChatDatas[^ 1] = new EncryptionChatData()
/// <summary> /// Сохраняет и рассылает сообщение всем подключеннымк чату пользователям /// </summary> /// <param name="chatId">Идентификатор чата</param> /// <param name="message">Данные сообщения для передачи</param> public async Task SendMessage(string chatId, ExtMessage message) { User user = Context.GetHttpContext().GetUser(); if (user == null) { return; } Chat chat = await _database.Chats.FirstOrDefaultAsync(p => p.Id == chatId); if (chat == null) { await Clients.Caller.SendAsync("ChatError", ResponseUtilities.GetErrorResponse(RequestError.ChatNotFound)).ConfigureAwait(false); return; } Message internalMessage = new Message() { Chat = chat, Date = DateTime.Now, EncryptedMessage = message.encryptedMessage, Id = RandomUtilities.GetCryptoRandomString(40), Sender = _database.Users.First(p => p.Id == user.Id), Status = MessageStatus.Encrypted }; chat.LastMessageDate = internalMessage.Date; chat.LastMessageId = internalMessage.Id; _database.Messages.Add(internalMessage); await _database.SaveChangesAsync(); KeySession[] keySessions = chat.EncryptionChatDatas.Where(p => p.KeySession != null).Select(p => p.KeySession).ToArray(); User[] users = await _database.Users.Where(p => keySessions.Contains(p.KeySession)).ToArrayAsync(); for (int i = 0; i < users.Length; i++) { await Clients.User(users[i].Id).SendAsync("NewMessage", chatId, (ExtMessage)internalMessage); } }
public async Task <ActionResult <MainResponse> > UserRegister(UserRegisterRequest registerRequest) { if (_context.Users.Any(p => p.Login == registerRequest.Login)) { return(MainResponse.GetError(Enums.RequestError.LoginExists)); } RSAKeyPair keyPair = new RSAKeyPair() { EncryptedPrivateKey = registerRequest.EncryptedPrivateKey, LastKeyPair = null, LastPublicKeySign = null, PublicKey = registerRequest.PublicKey }; _context.RSAKeyPairs.Add(keyPair); User user = new User() { Id = Hash.Sha1(Hash.Sha256(registerRequest.Login + RandomUtilities.GetCryptoRandomString(53))), RegistrationDate = DateTime.Now, Email = registerRequest.Email, FirstName = registerRequest.FirstName, LastName = registerRequest.LastName, Login = registerRequest.Login, HashKeySeed = registerRequest.HashKeySeed, UserSalt = RandomUtilities.GetCryptoRandomString(16), IdentificationWord = registerRequest.IdentificationWord, UserIv = registerRequest.Iv, AvailableKeys = 1000, RSAKeyPair = keyPair }; user.Password = GetPassword(registerRequest.Password, user.UserSalt); _context.Users.Add(user); await _context.SaveChangesAsync().ConfigureAwait(false); return(MainResponse.GetSuccess()); }
public async Task <ActionResult <MainResponse> > UserLogin(UserLoginRequest loginRequest) { User user = await _context.Users.FirstOrDefaultAsync(p => p.Login == loginRequest.Login); if (user == null) { return(MainResponse.GetError(Enums.RequestError.UserNotFound)); } string assumedPassword = GetPassword(loginRequest.Password, user.UserSalt); if (assumedPassword != user.Password) { return(MainResponse.GetError(Enums.RequestError.UserNotFound)); } Auth auth = new Auth() { Expire = DateTime.Now.AddSeconds(_serverConfig.Users.TokenExpirationTime), LocalDataEncryptionKey = RandomUtilities.GetCryptoRandomString(40), Token = RandomUtilities.GetCryptoRandomString(32), RefreshToken = RandomUtilities.GetCryptoRandomString(64), }; user.UserState = Enums.UserStates.SecretKey; _context.Auth.Add(auth); await _context.SaveChangesAsync(); user.Auth.Add(auth); _context.Users.Update(user); await _context.SaveChangesAsync(); UserLoginResponse userLoginResponse = new UserLoginResponse() { UserIV = user.UserIv, UserSalt = user.UserSalt, IdentificationWord = user.IdentificationWord, HashKey = GethashKey(user.HashKeySeed, _serverConfig.General.HashKeyLength), EncryptedPrivateKey = user.RSAKeyPair.EncryptedPrivateKey, PublicKey = user.RSAKeyPair.PublicKey, KeyId = user.RSAKeyPair.Id, EncryptionKey = auth.LocalDataEncryptionKey }; HttpContext.Response.Cookies.Append("refresh-token", auth.RefreshToken, new CookieOptions() { Domain = coockieDomain, HttpOnly = true, Path = "/api/auth/token-refresh" }); HttpContext.Response.Cookies.Append("auth-token", auth.Token, new CookieOptions() { Domain = coockieDomain, HttpOnly = true, Path = "/api" }); HttpContext.Response.Cookies.Append("auth-token", auth.Token, new CookieOptions() { Domain = coockieDomain, HttpOnly = true, Path = "/sockets" }); return(MainResponse.GetSuccess(userLoginResponse)); }