aboutsummaryrefslogtreecommitdiff
path: root/src/DevHive.Services/Services/UserService.cs
blob: 960630e342b813a1dcfa6c3712a5adcb5ac21aa6 (plain) (blame)
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
using AutoMapper;
using DevHive.Services.Options;
using DevHive.Services.Models.Identity.User;
using System.Threading.Tasks;
using DevHive.Data.Models;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Collections.Generic;
using DevHive.Common.Models.Identity;
using DevHive.Services.Interfaces;
using DevHive.Data.Interfaces.Repositories;
using System.Linq;
using DevHive.Common.Models.Misc;
using DevHive.Services.Models.Language;
using DevHive.Services.Models.Technology;
using DevHive.Services.Models.Identity.Role;

namespace DevHive.Services.Services
{
	public class UserService : IUserService
	{
		private readonly IUserRepository _userRepository;
		private readonly IRoleRepository _roleRepository;
		private readonly ILanguageRepository _languageRepository;
		private readonly ITechnologyRepository _technologyRepository;
		private readonly IMapper _userMapper;
		private readonly JWTOptions _jwtOptions;

		public UserService(IUserRepository userRepository,
			ILanguageRepository languageRepository,
			IRoleRepository roleRepository,
			ITechnologyRepository technologyRepository,
			IMapper mapper,
			JWTOptions jwtOptions)
		{
			this._userRepository = userRepository;
			this._roleRepository = roleRepository;
			this._userMapper = mapper;
			this._jwtOptions = jwtOptions;
			this._languageRepository = languageRepository;
			this._technologyRepository = technologyRepository;
		}

		#region Authentication

		public async Task<TokenModel> LoginUser(LoginServiceModel loginModel)
		{
			if (!await this._userRepository.DoesUsernameExistAsync(loginModel.UserName))
				throw new ArgumentException("Invalid username!");

			User user = await this._userRepository.GetByUsernameAsync(loginModel.UserName);

			if (user.PasswordHash != PasswordModifications.GeneratePasswordHash(loginModel.Password))
				throw new ArgumentException("Incorrect password!");

			return new TokenModel(WriteJWTSecurityToken(user.Id, user.Roles));
		}

		public async Task<TokenModel> RegisterUser(RegisterServiceModel registerModel)
		{
			if (await this._userRepository.DoesUsernameExistAsync(registerModel.UserName))
				throw new ArgumentException("Username already exists!");

			if (await this._userRepository.DoesEmailExistAsync(registerModel.Email))
				throw new ArgumentException("Email already exists!");

			User user = this._userMapper.Map<User>(registerModel);
			user.PasswordHash = PasswordModifications.GeneratePasswordHash(registerModel.Password);

			// Make sure the default role exists
			if (!await this._roleRepository.DoesNameExist(Role.DefaultRole))
				await this._roleRepository.AddAsync(new Role { Name = Role.DefaultRole });

			// Set the default role to the user
			Role defaultRole = await this._roleRepository.GetByNameAsync(Role.DefaultRole);
			user.Roles = new HashSet<Role>() { defaultRole };

			await this._userRepository.AddAsync(user);

			return new TokenModel(WriteJWTSecurityToken(user.Id, user.Roles));
		}
		#endregion

		#region Read
		public async Task<UserServiceModel> GetUserById(Guid id)
		{
			User user = await this._userRepository.GetByIdAsync(id)
				?? throw new ArgumentException("User does not exist!");

			return this._userMapper.Map<UserServiceModel>(user);
		}

		public async Task<UserServiceModel> GetUserByUsername(string username)
		{
			User friend = await this._userRepository.GetByUsernameAsync(username);

			if (friend == null)
				throw new ArgumentException("User does not exist!");

			return this._userMapper.Map<UserServiceModel>(friend);
		}
		#endregion

		#region Update
		public async Task<UserServiceModel> UpdateUser(UpdateUserServiceModel updateUserServiceModel)
		{
			await this.ValidateUserOnUpdate(updateUserServiceModel);

			await this.ValidateUserCollections(updateUserServiceModel);

			updateUserServiceModel = await this.PopulateUpdateModelWithIds(updateUserServiceModel);

			User user = this._userMapper.Map<User>(updateUserServiceModel);

			bool successful = await this._userRepository.EditAsync(updateUserServiceModel.Id, user);

			if (!successful)
				throw new InvalidOperationException("Unable to edit user!");

			return this._userMapper.Map<UserServiceModel>(user);
		}
		#endregion

		#region Delete
		public async Task DeleteUser(Guid id)
		{
			if (!await this._userRepository.DoesUserExistAsync(id))
				throw new ArgumentException("User does not exist!");

			User user = await this._userRepository.GetByIdAsync(id);
			bool result = await this._userRepository.DeleteAsync(user);

			if (!result)
				throw new InvalidOperationException("Unable to delete user!");
		}
		#endregion

		#region Validations
		public async Task<bool> ValidJWT(Guid id, string rawTokenData)
		{
			// There is authorization name in the beginning, i.e. "Bearer eyJh..."
			var jwt = new JwtSecurityTokenHandler().ReadJwtToken(rawTokenData.Remove(0, 7));

			Guid jwtUserID = new Guid(this.GetClaimTypeValues("ID", jwt.Claims).First());
			List<string> jwtRoleNames = this.GetClaimTypeValues("role", jwt.Claims);

			User user = await this._userRepository.GetByIdAsync(jwtUserID)
				?? throw new ArgumentException("User does not exist!");

			/* Check if user is trying to do something to himself, unless he's an admin */

			/* Check roles */
			if (jwtRoleNames.Contains(Role.AdminRole))
				return true;

			if (!jwtRoleNames.Contains(Role.AdminRole))
				if (user.Id != id)
					return false;

			// Check if jwt contains all user roles (if it doesn't, jwt is either old or tampered with)
			foreach (var role in user.Roles)
			{
				if (!jwtRoleNames.Contains(role.Name))
					return false;
			}

			// Check if jwt contains only roles of user
			if (jwtRoleNames.Count != user.Roles.Count)
				return false;

			return true;
		}

		private List<string> GetClaimTypeValues(string type, IEnumerable<Claim> claims)
		{
			List<string> toReturn = new();

			foreach (var claim in claims)
				if (claim.Type == type)
					toReturn.Add(claim.Value);

			return toReturn;
		}

		private async Task ValidateUserOnUpdate(UpdateUserServiceModel updateUserServiceModel)
		{
			if (!await this._userRepository.DoesUserExistAsync(updateUserServiceModel.Id))
				throw new ArgumentException("User does not exist!");

			if (!this._userRepository.DoesUserHaveThisUsername(updateUserServiceModel.Id, updateUserServiceModel.UserName)
					&& await this._userRepository.DoesUsernameExistAsync(updateUserServiceModel.UserName))
				throw new ArgumentException("Username already exists!");
		}

		private async Task ValidateUserCollections(UpdateUserServiceModel updateUserServiceModel)
		{
			//Do NOT allow a user to change his roles, unless he is an Admin
			bool isAdmin = (await this._userRepository.GetByIdAsync(updateUserServiceModel.Id))
				.Roles.Any(r => r.Name == Role.AdminRole);

			if (isAdmin)
			{
				// Roles
				foreach (var role in updateUserServiceModel.Roles)
				{
					Role returnedRole = await this._roleRepository.GetByNameAsync(role.Name) ??
						throw new ArgumentException($"Role {role.Name} does not exist!");
				}
			}
			//Preserve original user roles
			else
			{
				HashSet<Role> roles = (await this._userRepository.GetByIdAsync(updateUserServiceModel.Id)).Roles;

				foreach (var role in roles)
				{
					Role returnedRole = await this._roleRepository.GetByNameAsync(role.Name) ??
						throw new ArgumentException($"Role {role.Name} does not exist!");
				}
			}

			// Friends
			foreach (var friend in updateUserServiceModel.Friends)
			{
				User returnedFriend = await this._userRepository.GetByUsernameAsync(friend.UserName) ??
					throw new ArgumentException($"User {friend.UserName} does not exist!");
			}

			// Languages
			foreach (var language in updateUserServiceModel.Languages)
			{
				Language returnedLanguage = await this._languageRepository.GetByNameAsync(language.Name) ??
					throw new ArgumentException($"Language {language.Name} does not exist!");
			}

			// Technology
			foreach (var technology in updateUserServiceModel.Technologies)
			{
				Technology returnedTechnology = await this._technologyRepository.GetByNameAsync(technology.Name) ??
					throw new ArgumentException($"Technology {technology.Name} does not exist!");
			}
		}

		private string WriteJWTSecurityToken(Guid userId, HashSet<Role> roles)
		{
			byte[] signingKey = Encoding.ASCII.GetBytes(_jwtOptions.Secret);

			HashSet<Claim> claims = new()
			{
				new Claim("ID", $"{userId}"),
			};

			foreach (var role in roles)
			{
				claims.Add(new Claim(ClaimTypes.Role, role.Name));
			}

			SecurityTokenDescriptor tokenDescriptor = new()
			{
				Subject = new ClaimsIdentity(claims),
				Expires = DateTime.Today.AddDays(7),
				SigningCredentials = new SigningCredentials(
					new SymmetricSecurityKey(signingKey),
					SecurityAlgorithms.HmacSha512Signature)
			};

			JwtSecurityTokenHandler tokenHandler = new();
			SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
			return tokenHandler.WriteToken(token);
		}
		#endregion

		#region Misc
		public async Task<Guid> SuperSecretPromotionToAdmin(Guid userId)
		{
			User user = await this._userRepository.GetByIdAsync(userId) ??
				throw new ArgumentException("User does not exist! Can't promote shit in this country...");

			if (!await this._roleRepository.DoesNameExist("Admin"))
			{
				Role adminRole = new()
				{
					Name = Role.AdminRole
				};
				adminRole.Users.Add(user);

				await this._roleRepository.AddAsync(adminRole);
			}

			Role admin = await this._roleRepository.GetByNameAsync(Role.AdminRole);

			user.Roles.Add(admin);
			await this._userRepository.EditAsync(user.Id, user);

			return admin.Id;
		}

		private async Task<UpdateUserServiceModel> PopulateUpdateModelWithIds(UpdateUserServiceModel updateUserServiceModel)
		{
			/* Roles */
			int roleCount = updateUserServiceModel.Roles.Count;
			for (int i = 0; i < roleCount; i++)
			{
				Role role = await this._roleRepository.GetByNameAsync(updateUserServiceModel.Roles.ElementAt(i).Name) ??
					throw new ArgumentException("Invalid role name!");

				updateUserServiceModel.Roles.ElementAt(i).Id = role.Id;
			}

			/* Languages */
			int langCount = updateUserServiceModel.Languages.Count;
			for (int i = 0; i < langCount; i++)
			{
				Language language = await this._languageRepository.GetByNameAsync(updateUserServiceModel.Languages.ElementAt(i).Name) ??
					throw new ArgumentException("Invalid language name!");

				updateUserServiceModel.Languages.ElementAt(i).Id = language.Id;
			}

			/* Technologies */
			int techCount = updateUserServiceModel.Technologies.Count;
			for (int i = 0; i < techCount; i++)
			{
				Technology technology = await this._technologyRepository.GetByNameAsync(updateUserServiceModel.Technologies.ElementAt(i).Name) ??
					throw new ArgumentException("Invalid technology name!");

				updateUserServiceModel.Technologies.ElementAt(i).Id = technology.Id;
			}

			/* Friends */
			int friendsCount = updateUserServiceModel.Friends.Count;
			for (int i = 0; i < friendsCount; i++)
			{
				User friend = await this._userRepository.GetByUsernameAsync(updateUserServiceModel.Friends.ElementAt(i).UserName) ??
					throw new ArgumentException("Invalid friend's username!");

				updateUserServiceModel.Friends.ElementAt(i).Id = friend.Id;
			}

			return updateUserServiceModel;
		}
		#endregion
	}
}