aboutsummaryrefslogtreecommitdiff
path: root/Timeline/Services/UserService.cs
blob: ad36c37bb5d6d7ec85346060d898282ae497ce04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
using Timeline.Entities;
using Timeline.Models;

namespace Timeline.Services
{
    public class CreateTokenResult
    {
        public string Token { get; set; }
        public UserInfo UserInfo { get; set; }
    }

    public enum CreateUserResult
    {
        Success,
        AlreadyExists
    }

    public interface IUserService
    {
        /// <summary>
        /// Try to anthenticate with the given username and password.
        /// If success, create a token and return the user info.
        /// </summary>
        /// <param name="username">The username of the user to be anthenticated.</param>
        /// <param name="password">The password of the user to be anthenticated.</param>
        /// <returns>Return null if anthentication failed. An <see cref="CreateTokenResult"/> containing the created token and user info if anthentication succeeded.</returns>
        Task<CreateTokenResult> CreateToken(string username, string password);

        /// <summary>
        /// Verify the given token.
        /// If success, return the user info.
        /// </summary>
        /// <param name="token">The token to verify.</param>
        /// <returns>Return null if verification failed. The user info if verification succeeded.</returns>
        Task<UserInfo> VerifyToken(string token);

        Task<CreateUserResult> CreateUser(string username, string password, string[] roles);
    }

    public class UserService : IUserService
    {
        private readonly ILogger<UserService> _logger;
        private readonly DatabaseContext _databaseContext;
        private readonly IJwtService _jwtService;
        private readonly IPasswordService _passwordService;

        public UserService(ILogger<UserService> logger, DatabaseContext databaseContext, IJwtService jwtService, IPasswordService passwordService)
        {
            _logger = logger;
            _databaseContext = databaseContext;
            _jwtService = jwtService;
            _passwordService = passwordService;
        }

        public async Task<CreateTokenResult> CreateToken(string username, string password)
        {
            var users = _databaseContext.Users.ToList();

            var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();

            if (user == null)
            {
                _logger.LogInformation($"Create token failed with invalid username. Username = {username} Password = {password} .");
                return null;
            }

            var verifyResult = _passwordService.VerifyPassword(user.EncryptedPassword, password);

            if (verifyResult)
            {
                var userInfo = new UserInfo(user);

                return new CreateTokenResult
                {
                    Token = _jwtService.GenerateJwtToken(user.Id, userInfo.Roles),
                    UserInfo = userInfo
                };
            }
            else
            {
                _logger.LogInformation($"Create token failed with invalid password. Username = {username} Password = {password} .");
                return null;
            }
        }

        public async Task<UserInfo> VerifyToken(string token)
        {
            var userId = _jwtService.VerifyJwtToken(token);

            if (userId == null)
            {
                _logger.LogInformation($"Verify token falied. Reason: invalid token. Token: {token} .");
                return null;
            }

            var user = await _databaseContext.Users.Where(u => u.Id == userId.Value).SingleOrDefaultAsync();

            if (user == null)
            {
                _logger.LogInformation($"Verify token falied. Reason: invalid user id. UserId: {userId} Token: {token} .");
                return null;
            }

            return new UserInfo(user);
        }

        public async Task<CreateUserResult> CreateUser(string username, string password, string[] roles)
        {
            var exists = (await _databaseContext.Users.Where(u => u.Name == username).ToListAsync()).Count != 0;

            if (exists)
            {
                return CreateUserResult.AlreadyExists;
            }

            await _databaseContext.Users.AddAsync(new User { Name = username, EncryptedPassword = _passwordService.HashPassword(password), RoleString = string.Join(',', roles) });
            await _databaseContext.SaveChangesAsync();

            return CreateUserResult.Success;
        }
    }
}