Exemplo n.º 1
0
        public async Task <IActionResult> Login([FromBody] LoginModel user)
        {
            if (user == null)
            {
                return(BadRequest("Invalid client request"));
            }

            if (await botService.CheckUserLogin(user.UserName, user.Password))
            {
                var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue("jwtKey", Defaults.JwtKey)));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokeOptions = new JwtSecurityToken(
                    issuer: "http://localhost:5000",
                    audience: "http://localhost:5000",
                    claims: new List <Claim>(),
                    expires: DateTime.Now.AddMinutes(5),
                    signingCredentials: signinCredentials
                    );

                Database.Models.User fuser = context.Users.First(u => u.Name == user.UserName);

                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                cache.AssignedTokens[tokenString] = fuser;
                return(Ok(new { Token = tokenString, User = fuser }));
            }
            else
            {
                return(Unauthorized());
            }
        }
        public async Task UpdateAsync(Database.Models.User data)
        {
            data.ThrowIfNull(nameof(data));

            data.ThrowIfInvalid();

            Database.Models.User user = await ActiveUserByUserNameAsync(data.UserName);

            if (user != null)
            {
                user.Update(
                    firstName: data.FirstName,
                    lastName: data.LastName);

                var userRole = _context.UserRoles.Where(x => x.UserId == user.Id);

                if (user.Role != data.Role)
                {
                    _context.UserRoles.RemoveRange(userRole);

                    await _context.UserRoles.AddAsync(new IdentityUserRole <long>()
                    {
                        UserId = data.Id,
                        RoleId = (long)data.Role
                    });
                }

                await _context.SaveChangesAsync();
            }
        }
Exemplo n.º 3
0
        public static TokenData BuildUserToken(IConfig conf, Database.Models.User user)
        {
            var config = conf.Get();

            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim("DiscordId", user.Id.ToString()),
                new Claim("Player", "waifu_player"),
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.Jwt.Key));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(config.Jwt.Issuer,
                                             config.Jwt.Issuer,
                                             claims,
                                             expires: DateTime.Now.AddMinutes(30),
                                             signingCredentials: creds);

            return(new TokenData()
            {
                Token = new JwtSecurityTokenHandler().WriteToken(token),
                Expire = token.ValidTo
            });
        }
Exemplo n.º 4
0
        private ICollection <Database.Models.Task> GetTaskList(TaskContext context, Database.Models.User user)
        {
            IQueryable <Database.Models.UserTaskMap> utmaps = context.UserTaskMaps.Include(utm => utm.Task).Where(utm => utm.UserID == user.ID);
            var tl = utmaps.Select(utm => utm.Task).ToList();

            return(tl);
        }
Exemplo n.º 5
0
        private async Task <UserCredentialsReply> RegisterUser(string email, string password, string name, bool isGoogle, string imageUrl = null)
        {
            var user = new Database.Models.User
            {
                Email      = email,
                Name       = name,
                Password   = isGoogle ? "" : _hasher.Hash(password),
                Registered = DateTime.UtcNow,
                IsGoogle   = isGoogle,
                ImageUrl   = imageUrl,
                RoleId     = (int)Roles.User
            };

            _db.Users.Add(user);
            await _db.SaveChangesAsync();

            var refreshToken = GenerateRefreshToken(user.UserId);

            _db.Tokens.Add(refreshToken);

            await _db.SaveChangesAsync();

            return(new UserCredentialsReply
            {
                UserId = user.UserId,
                Email = user.Email,
                Name = user.Name,
                Token = CreateToken(user.UserId),
                RefreshToken = refreshToken.Token,
                IsGoogle = user.IsGoogle,
                RoleId = user.RoleId
            });
        }
Exemplo n.º 6
0
        private void UpdateUser(Database.Models.User user, Message message, ITelegramBotClient telegramBotClient)
        {
            int    icqDelta;
            string changeText;

            if (IsPositive())
            {
                icqDelta   = random.Next(1, 12);
                changeText = "увеличился";
            }
            else
            {
                icqDelta   = random.Next(-9, -1);
                changeText = "уменьшился";
            }

            var newIcq = user.Icq + icqDelta;

            if (newIcq <= 0)
            {
                newIcq = 0;
            }

            user.Icq            = newIcq;
            user.Name           = message.From.GetFullName();
            user.LastIcqDelta   = icqDelta;
            user.TotalPlayed   += 1;
            user.LastTimePlayed = DateTime.Now.ToUniversalTime();

            telegramBotClient.SendTextMessage(message.Chat.Id, $"{user.Name}, Ваш ICQ {changeText} на {Math.Abs(icqDelta)} и теперь равен {user.Icq}, поздравляем!");

            context.Users.Update(user);
        }
Exemplo n.º 7
0
        public async Task <Stream> GetProfileImageAsync(SocketGuildUser user, Database.Models.User botUser, long topPosition)
        {
            var response = await _shClient.User.GetAsync(botUser.Shinden);

            using (var image = await _img.GetUserProfileAsync(response.Body, botUser, user.GetAvatarUrl().Split("?")[0],
                                                              topPosition, user.Nickname ?? user.Username, user.Roles.OrderByDescending(x => x.Position).First().Color))
            {
                return(image.ToPngStream());
            }
        }
Exemplo n.º 8
0
        public async Task <Stream> GetProfileImageAsync(SocketGuildUser user, Database.Models.User botUser, long topPosition)
        {
            var response = await _shClient.User.GetAsync(botUser.Shinden);

            using (var image = await _img.GetUserProfileAsync(response.Body, botUser, user.GetAvatarUrl()?.Split("?")[0] ?? "https://i.imgur.com/xVIMQiB.jpg",
                                                              topPosition, user.Nickname ?? user.Username, user.Roles.OrderByDescending(x => x.Position).FirstOrDefault()?.Color ?? Discord.Color.DarkerGrey))
            {
                return(image.ToPngStream());
            }
        }
Exemplo n.º 9
0
        public async Task <Database.Models.User> UserByEmailOrCreateAsync(GoogleClaims claimsUser)
        {
            claimsUser.ThrowIfNull(nameof(claimsUser));

            Database.Models.User user =
                await ByEmailOrNullAsync(claimsUser.Email) ??
                await CreateUserAsync(claimsUser);

            return(user);
        }
Exemplo n.º 10
0
        public async Task <bool> AddUserToProject(Database.Models.User user, Database.Models.Project project)
        {
            if (user == null || user.Id == 0 || project == null)
            {
                throw new Exception("Can't perform this action");
            }
            await _projectRepository.AddUserToProjectAsync(user.Id, project.Id);

            return(true);
        }
Exemplo n.º 11
0
        internal async Task SendMessageAsync(string message, int userId)
        {
            using (IServiceScope scope = provider.CreateScope())
            {
                TaskContext          context = scope.ServiceProvider.GetService <TaskContext>();
                Database.Models.User user    = context.Users.First(u => u.ID == userId);
                var pm = await Driver.CreatePrivateMessageAsync(user.Name);

                var result = await Driver.SendMessageAsync(message, pm.Result.RoomId);
            }
        }
        public async Task DeleteAsync(string userName)
        {
            Database.Models.User user = await ActiveUserByUserNameAsync(userName);

            if (user != null)
            {
                user.DeletedAt = DateTimeOffset.Now;

                await _context.SaveChangesAsync();
            }
        }
        public async Task RemoveAsync(string userName)
        {
            Database.Models.User user = await InactiveUserByUserNameAsync(userName);

            if (user != null)
            {
                _context.Remove(user);

                await _context.SaveChangesAsync();
            }
        }
        public async Task RestoreAsync(string userName)
        {
            Database.Models.User user = await InactiveUserByUserNameAsync(userName);

            if (user != null)
            {
                user.DeletedAt = null;

                await _context.SaveChangesAsync();
            }
        }
Exemplo n.º 15
0
        public GoogleClaims ReadUser(Database.Models.User user)
        {
            user.ThrowIfNull(nameof(user));

            _claims.Add(new Claim(CustomClaimTypes.Username, user.UserName));
            _claims.Add(new Claim(ClaimTypes.Role, user.Role.ToString()));

            _claims = _claims.Where(x => x.Type != ClaimTypes.NameIdentifier).ToList();
            _claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));

            return this;
        }
Exemplo n.º 16
0
        public async Task <bool> UpdateUserData(Database.Models.User user)
        {
            var unique = await _checkInputService.UniqueUsername(user);

            if (!unique)
            {
                return(false);
            }
            await _userRepository.UpdateUserAsync(user);

            return(true);
        }
Exemplo n.º 17
0
        public async Task <int> AddUser(Database.Models.User user)
        {
            var uniqueNickname = await _checkInputService.UniqueUsername(user);

            if (!uniqueNickname)
            {
                return(0);
            }
            var id = await _userRepository.AddUserAsync(user);

            return(id);
        }
Exemplo n.º 18
0
        public async Tasks.Task SendTaskUpdatedMessage(Task task, Database.Models.User initiator)
        {
            var sendusers = task.Assignees.Select(x => x.User).ToList();

            if (task.Assignees.FirstOrDefault(x => task.InitiatorID == x.UserID) == null)
            {
                sendusers.Add(task.Initiator);
            }

            foreach (Database.Models.User user in sendusers)
            {
                await SendMessageToUser(user.ID, $"Task {task.ID} has been updated");
            }
        }
Exemplo n.º 19
0
 private Task CreateUserTask(SocketGuildUser user)
 {
     return(new Task(() =>
     {
         using (var db = new Database.UserContext(_config))
         {
             if (!db.Users.Any(x => x.Id == user.Id))
             {
                 var bUser = new Database.Models.User().Default(user.Id);
                 db.Users.Add(bUser);
                 db.SaveChanges();
             }
         }
     }));
 }
Exemplo n.º 20
0
        public ExactOrder XMLToDBOrder(OrderXML orderXml, UserVM user, Database.Models.User dbUser, Guid SupplierId)
        {
            var order = new ExactOrder()
            {
                Description     = orderXml.Description,
                Created         = DateTime.Now,
                Currency        = orderXml.Currency,
                TimeSend        = DateTime.Now,
                OrderDate       = DateTime.Now,
                DBUser          = dbUser,
                IsStoredInExact = false,
                ItemsAreInExact = false,
                CreatorId       = user.CreatorId,
                Supplier        = new ExactSupplier
                {
                    ExactId = SupplierId,
                },
            };

            var orderLines = new List <ExactOrderLine>();

            foreach (var x in orderXml.OrderLines)
            {
                var line = new ExactOrderLine
                {
                    Item = new ExactItem
                    {
                        Name        = x.Item,
                        ExactUserId = new Guid(user.CreatorId),
                        SupplierId  = new Guid(user.SupplierId),
                    },
                    Description   = x.Description,
                    AmountDC      = x.AmountDC,
                    Unit          = x.Unit,
                    NetPrice      = x.NetPrice,
                    ReceiptDate   = DateTime.Now,
                    VATAmount     = x.VATAmount,
                    VATCode       = x.VATCode,
                    VATPercentage = x.VATPercentage,
                    Quantity      = x.Quantity,
                };
                orderLines.Add(line);
            }

            order.Lines = orderLines;

            return(order);
        }
Exemplo n.º 21
0
        private async Task <Database.Models.User> GetUserAsync(int userId, TelegramDbContext context)
        {
            var user = await context.Users.FirstOrDefaultAsync(x => x.TelegramId == userId);

            if (user == null)
            {
                _logger.LogInformation("Got message from a new user with id {0}", userId);
                _logger.LogInformation("Adding user {0} to database...", userId);

                user = new Database.Models.User {
                    TelegramId = userId
                };
                await context.Users.AddAsync(user);

                await context.SaveChangesAsync();
            }

            return(user);
        }
Exemplo n.º 22
0
        private async Task <UserCredentialsReply> LoginUser(Database.Models.User user)
        {
            var oldToken = await _db.Tokens.FirstOrDefaultAsync(x => x.UserId == user.UserId);

            RefreshOldToken(oldToken);
            _db.Update(oldToken);
            await _db.SaveChangesAsync();

            return(new UserCredentialsReply
            {
                UserId = user.UserId,
                Email = user.Email,
                Name = user.Name,
                Token = CreateToken(user.UserId),
                RefreshToken = oldToken.Token,
                IsGoogle = user.IsGoogle,
                RoleId = user.RoleId
            });
        }
Exemplo n.º 23
0
        private void AddNewUser(Message message, ITelegramBotClient telegramBotClient)
        {
            var icq     = random.Next(1, 10);
            var newUser = new Database.Models.User
            {
                Id             = message.From.Id,
                Name           = message.From.GetFullName(),
                Icq            = icq,
                LastIcqDelta   = icq,
                TotalPlayed    = 1,
                TotalFailed    = 0,
                LastTimePlayed = DateTime.Now.ToUniversalTime()
            };

            telegramBotClient.SendTextMessage(message.Chat.Id, $"Добро пожаловать в игру \"ICQ Meter\", {newUser.Name}!");
            telegramBotClient.SendTextMessage(message.Chat.Id, $"{newUser.Name}, Ваш ICQ теперь равен {newUser.Icq}, поздравляем!");

            context.Users.Add(newUser);
        }
Exemplo n.º 24
0
        private void PunishUser(Database.Models.User user, Message message, ITelegramBotClient telegramBotClient)
        {
            var icqDelta = random.Next(-6, -2);
            var newIcq   = user.Icq + icqDelta;

            if (newIcq <= 0)
            {
                newIcq = 0;
            }

            user.Icq          = newIcq;
            user.Name         = message.From.GetFullName();
            user.LastIcqDelta = icqDelta;
            user.TotalPlayed += 1;
            user.TotalFailed += 1;

            telegramBotClient.SendTextMessage(message.Chat.Id, $"{user.Name}, Вы уже играли сегодня, поэтому Ваш ICQ уменьшился на {Math.Abs(icqDelta)} и теперь равен {user.Icq}, будьте внимательны!");

            context.Users.Update(user);
        }
Exemplo n.º 25
0
        // public is for test purposes.
        public async Task <Database.Models.User> CreateUserAsync(GoogleClaims claimsUser)
        {
            _emailDomainValidatorService.Validate(claimsUser.Email);

            Role userRole = await ChooseUserRoleAsync();

            var user = new Database.Models.User(
                firstName: claimsUser.GivenName,
                lastName: claimsUser.Surname,
                email: claimsUser.Email,
                role: userRole,
                emailConfirmed: true);

            claimsUser = claimsUser.ReadUser(user);

            IdentityResult createUserResult = await _userManager.CreateAsync(user);

            if (!createUserResult.Succeeded)
            {
                throw CreateException($"Cannot create new user '{claimsUser.Email}'\r\n", createUserResult);
            }

            string role = userRole.ToString();

            IdentityResult roleAddingResult = await _userManager.AddToRoleAsync(user, role);

            if (!roleAddingResult.Succeeded)
            {
                throw CreateException($"Cannot add role '{role}' to user '{claimsUser.Email}'\r\n", roleAddingResult);
            }

            IdentityResult claimsAddingResult = await _userManager.AddClaimsAsync(user, claimsUser);

            if (!claimsAddingResult.Succeeded)
            {
                throw CreateException($"Cannot add claims to user '{claimsUser.Email}'\r\n", claimsAddingResult);
            }

            return(user);
        }
Exemplo n.º 26
0
 public static UserReply ToReply(this Database.Models.User user) => new UserReply
 {
     UserId = user.UserId, Name = user.Name, ImageUrl = user.ImageUrl ?? ""
 };
Exemplo n.º 27
0
 private string CreateDoneUrl(Database.Models.Task x, Database.Models.User user) => ResponseUrl + $"/users/{user.ID}/setDone/{x.ID}";
Exemplo n.º 28
0
 public async Tasks.Task SendUnAssignedMessage(Database.Models.User user, Database.Models.Task task, Database.Models.User initiator)
 {
     await SendMessageToUser(user.ID, $"Your assignment to **Task {task.ID}**: {task.Title} has been removed.");
 }
Exemplo n.º 29
0
 public async Tasks.Task SendAssigneeMessage(Database.Models.User user, Database.Models.Task task, Database.Models.User initiator)
 {
     await SendMessageToUser(user.ID, $"You have ben assigned to **Task {task.ID}**: {task.Title}.");
 }
Exemplo n.º 30
0
        public async Task <bool> UniqueUsername(Database.Models.User user)
        {
            var foundUser = await _userRepository.GetUserByNickname(user.Nickname);

            return(foundUser == null);
        }