コード例 #1
0
        /// <summary>
        /// Creates new or updates existing user with permissions check.
        /// </summary>
        public async Task <User> SaveAsync(User user)
        {
            if (user.Id != 0)
            {
                var dbUser = await _context.Users.SingleOrNotFoundAsync(u => u.Id == user.Id, "User not found");

                if (user.UserName != "admin")
                {
                    dbUser.IsAdmin = user.IsAdmin;
                }
                dbUser.DailyGoal   = user.DailyGoal;
                dbUser.NewPassword = user.NewPassword;
                user = dbUser;
            }
            else
            {
                if (await _context.Users.AnyAsync(u => u.UserName == user.UserName))
                {
                    throw new BadRequestException("User already exists");
                }
                _context.Users.Add(user);
            }
            if (!string.IsNullOrEmpty(user.NewPassword))
            {
                user.PasswordHash = AccountRepository.HashPassword(user.NewPassword);
            }
            await _context.SaveChangesAsync();

            return(user);
        }
コード例 #2
0
        /// <summary>
        /// Registers a new user.
        /// </summary>
        public async Task <User> Register(LogonModel logon)
        {
            if (await _context.Users.AnyAsync(u => u.UserName == logon.UserName))
            {
                throw new BadRequestException("User already exists");
            }
            var passwordHash = HashPassword(logon.Password);
            var user         = new User
            {
                UserName     = logon.UserName,
                PasswordHash = passwordHash,
                IsAdmin      = false,
            };

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

            return(user);
        }
コード例 #3
0
        /// <summary>
        /// Creates or updates entry.
        /// </summary>
        public async Task <Entry> SaveAsync(Entry entry)
        {
            if (entry.Id == 0)
            {
                var user = await _context.Users.SingleOrNotFoundAsync(u => u.Id == _userId, "Current user not found");

                entry.User = user;
                _context.Entries.Add(entry);
            }
            else
            {
                var entryInDb = await getEntries()
                                .Include(e => e.User)
                                .SingleOrNotFoundAsync(e => e.Id == entry.Id, "Entry not found");

                _context.Entry(entryInDb).CurrentValues.SetValues(entry);
                entry = entryInDb;
            }
            await _context.SaveChangesAsync();

            return(entry);
        }