Skip to content

Commit 72240d1

Browse files
authored
Merge pull request #73 from AXECAC/aragami3070/Updates
Aragami3070/updates
2 parents 9dbc01b + dc1636d commit 72240d1

File tree

11 files changed

+179
-159
lines changed

11 files changed

+179
-159
lines changed

.editorconfig

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
root = true
2+
[*]
3+
indent_style = space
4+
indent_size = 4
5+
6+
[*.{md,csproj, json}]
7+
indent_size = 2

Context/Classes/BaseRepository.cs

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using Microsoft.EntityFrameworkCore;
2-
using DataBase;
32

43
namespace Context;
54

Context/Classes/UserRepository.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44
namespace Context;
55

66
// Class UserRepository
7-
public class UserRepository : BaseRepository<User> ,IUserRepository
7+
public class UserRepository : BaseRepository<User>, IUserRepository
88
{
99
private readonly TemplateDbContext Db;
1010

1111
public UserRepository(TemplateDbContext db) : base(db)
1212
{
1313
Db = db;
1414
}
15-
15+
1616
// GeUser user by email
1717
public async Task<User>? GetByEmail(string email)
1818
{

Controllers/Controllers/UserController.cs

+4-2
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ public async Task<IActionResult> GetUsers()
5252
public async Task<IActionResult> GetUserById(int id)
5353
{
5454
// Id validation (Bad Input)
55-
if (id < 1){
55+
if (id < 1)
56+
{
5657
// Return StatusCode 422
5758
return UnprocessableEntity();
5859
}
@@ -167,7 +168,8 @@ public async Task<IActionResult> Edit(User userModel, string oldEmail)
167168
public async Task<IActionResult> DeleteUser(int id)
168169
{
169170
// Id validation (Bad Input)
170-
if (id < 1){
171+
if (id < 1)
172+
{
171173
// Return StatusCode 422
172174
return UnprocessableEntity();
173175
}

Controllers/Program.cs

+10-8
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,11 @@
4141
});
4242
});
4343
// Cors for web frontend
44-
builder.Services.AddCors(options => {
44+
builder.Services.AddCors(options =>
45+
{
4546
options.AddDefaultPolicy(
46-
policy => {
47+
policy =>
48+
{
4749
policy.WithOrigins("http://localhost:5173")
4850
.AllowAnyHeader();
4951
});
@@ -70,19 +72,19 @@
7072
});
7173

7274
// Add my Services
73-
builder.Services.AddScoped<IUserRepository, UserRepository>();
74-
builder.Services.AddScoped<IUserServices, UserServices>();
75-
builder.Services.AddScoped<ITokenServices, TokenServices>();
76-
builder.Services.AddScoped<IHashingServices, HashingServices>();
77-
builder.Services.AddScoped<IAuthServices, AuthServices>();
75+
builder.Services.AddSingleton<IUserRepository, UserRepository>();
76+
builder.Services.AddSingleton<IUserServices, UserServices>();
77+
builder.Services.AddSingleton<ITokenServices, TokenServices>();
78+
builder.Services.AddSingleton<IHashingServices, HashingServices>();
79+
builder.Services.AddSingleton<IAuthServices, AuthServices>();
7880

7981
// Read connection string to pgsql db
8082
var connectionString = builder.Configuration.GetConnectionString("Postgres");
8183

8284

8385
// Connect to db
8486
builder.Services.AddDbContext<TemplateDbContext>(options =>
85-
options.UseNpgsql(connectionString));
87+
options.UseNpgsql(connectionString), ServiceLifetime.Singleton);
8688

8789
var app = builder.Build();
8890

DataBase/Response/BaseResponse.cs

+92
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,96 @@ public class BaseResponse<T> : IBaseResponse<T>
88
public StatusCodes StatusCode { get; set; }
99

1010
public T Data { get; set; }
11+
12+
// Ok response generate (200)
13+
public static BaseResponse<T> Ok(T data, string description = "")
14+
{
15+
return new BaseResponse<T>()
16+
{
17+
Data = data,
18+
StatusCode = StatusCodes.Ok,
19+
Description = description,
20+
};
21+
}
22+
23+
// Empty Ok response generate (200)
24+
public static BaseResponse<T> Ok(string description = "")
25+
{
26+
return new BaseResponse<T>()
27+
{
28+
StatusCode = StatusCodes.Ok,
29+
Description = description,
30+
};
31+
}
32+
33+
// Created response generate (201)
34+
public static BaseResponse<T> Created(T data, string description = "")
35+
{
36+
return new BaseResponse<T>()
37+
{
38+
Data = data,
39+
StatusCode = StatusCodes.Created,
40+
Description = description,
41+
};
42+
}
43+
44+
// Empty Created response generate (201)
45+
public static BaseResponse<T> Created(string description = "")
46+
{
47+
return new BaseResponse<T>()
48+
{
49+
StatusCode = StatusCodes.Created,
50+
Description = description,
51+
};
52+
}
53+
54+
// NoContent response generate (204)
55+
public static BaseResponse<T> NoContent(string description = "")
56+
{
57+
return new BaseResponse<T>()
58+
{
59+
StatusCode = StatusCodes.NoContent,
60+
Description = description,
61+
};
62+
}
63+
64+
// Unauthorized response generate (401)
65+
public static BaseResponse<T> Unauthorized(string description = "")
66+
{
67+
return new BaseResponse<T>()
68+
{
69+
StatusCode = StatusCodes.Unauthorized,
70+
Description = description,
71+
};
72+
}
73+
74+
// NotFound response generate (404)
75+
public static BaseResponse<T> NotFound(string description = "")
76+
{
77+
return new BaseResponse<T>()
78+
{
79+
StatusCode = StatusCodes.NotFound,
80+
Description = description,
81+
};
82+
}
83+
84+
// Conflict response generate (409)
85+
public static BaseResponse<T> Conflict(string description = "")
86+
{
87+
return new BaseResponse<T>()
88+
{
89+
StatusCode = StatusCodes.Conflict,
90+
Description = description,
91+
};
92+
}
93+
94+
// InternalServerError response generate (500)
95+
public static BaseResponse<T> InternalServerError(string description = "")
96+
{
97+
return new BaseResponse<T>()
98+
{
99+
StatusCode = StatusCodes.InternalServerError,
100+
Description = description,
101+
};
102+
}
11103
}

DataBase/Response/IBaseResponse.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ namespace DataBase;
33
// Interface IBaseResponse
44
public interface IBaseResponse<T>
55
{
6-
StatusCodes StatusCode { get; }
7-
T Data { get; }
6+
string Description { get; }
7+
StatusCodes StatusCode { get; }
8+
T Data { get; }
89
}

Fixes.md

+25-55
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,39 @@
1-
добавить enum на statusCode
1+
- МБ потом: почитать middleware для обработки ошибок (вместо try|catch) и для авторизации
22

3+
- baseresponse -> статический фабричный метод
34

4-
operation result --- посмотреть варианты
5+
BaseResponse<T>.Ok();
56

6-
builder.Services.AddSingleton --- посмотреть
7+
Написать BaseResponse.Ok() класс без поля data
78

8-
Посмотреть
99

10-
https://github.com/OfferingSolutions/Entity-Framework-Core-Generic-Repository
11-
https://github.com/OfferingSolutions/Entity-Framework-Core-Generic-Repository/blob/master/OfferingSolutions.GenericEFCore/RepositoryBase/GenericRepositoryBase.cs
12-
https://github.com/OfferingSolutions/Entity-Framework-Core-Generic-Repository/blob/master/OfferingSolutions.GenericEFCore.SampleApp/ExampleRepositories/PersonRepository.cs
10+
- Переписать поиск по Id и по Email на...
11+
```cs
12+
public async Task<T>? FirstOrDefaultAsync(Expression<Func<T, bool>> expression)
13+
{
14+
return await Db.Set<T>().FirstOrDefaultAsync(expression);
1315

16+
}
17+
```
18+
В BaseRepository
1419

15-
Переделать UserRepository -> BaseRepository
20+
- В BaseRepository стоит добавить метод IQuariable<T> Where(Expresion)
21+
- IQuariable Select(Expresion)
1622

1723
```cs
18-
return await Db.Users.FirstOrDefaultAsync(x => x.Email == email);
19-
```
20-
->
21-
```cs
22-
return await Db.Set<T>().FirstOrDefaultAsync(x => x.Email == email);
24+
using System.Collections.Generic;
25+
// Достать Id всех юзеров с именем Alex
26+
var .. = await UserRepository
27+
.Where(x => x.FirstName == "Alex")
28+
.Select(x => x.Id)
29+
.ToListAsync();
2330
```
2431

25-
controller IResult -> IActionResult
26-
2732
```cs
28-
public class UserController : Controller
29-
{
30-
private readonly IUserServices _UserServices;
31-
32-
public UserController(IUserServices userServices)
33-
{
34-
_UserServices = userServices;
35-
}
36-
37-
// GetUsers method
38-
[HttpGet]
39-
public async Task<IActionResult> GetUsers()
40-
{
41-
var response = await _UserServices.GetUsers();
42-
43-
// Some Users found
44-
if (response.StatusCode == 200)
45-
{
46-
// Return response 200
47-
return Ok(response.Data.ToList());
48-
}
49-
// 0 Users found
50-
if (response.StatusCode == 204)
51-
{
52-
// Return response 200
53-
return Ok();
54-
}
55-
// Return StatusCode 500
56-
return StatusCode(statusCode: response.StatusCode);
57-
}
58-
}
33+
// Достать всех юзеров с Id > 10 группируя по имени
34+
var .. = await UserRepository
35+
.Where(x => Id > 10)
36+
.GroupBy(x => x.FirstName)
37+
.ToListAsync();
5938
```
6039

61-
62-
почитать middleware для обработки ошибок (вместо try|catch) и для авторизации
63-
64-
65-
Хеширование паролей через отдельный сервис
66-
67-
baseresponse -> статический фабричный метод
68-
69-
BaseResponse<T>.Ok();

Services/Implementations/AuthServices.cs

+9-25
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ public async Task<IBaseResponse<string>> TryRegister(User user, string secretKey
2222
// Hashing Password
2323
user = _HashingServices.Hashing(user);
2424

25-
var baseResponse = new BaseResponse<string>();
25+
BaseResponse<string> baseResponse;
2626
try
2727
{
2828
// Find new user email
@@ -34,27 +34,20 @@ public async Task<IBaseResponse<string>> TryRegister(User user, string secretKey
3434
// Create new user
3535
await _UserRepository.Create(user);
3636
// Created (201)
37-
baseResponse.StatusCode = StatusCodes.Created;
38-
// For JWT token in future
39-
baseResponse.Data = _TokenServices.GenereteJWTToken(user, secretKey);
37+
baseResponse = BaseResponse<string>.Created(data: _TokenServices.GenereteJWTToken(user, secretKey));
4038
}
4139
// This email already exists
4240
else
4341
{
4442
// Conflict (409)
45-
baseResponse.StatusCode = StatusCodes.Conflict;
46-
baseResponse.Description = "This email already exists";
43+
baseResponse = BaseResponse<string>.Conflict("This email already exists");
4744
}
4845
return baseResponse;
4946
}
5047
catch (Exception ex)
5148
{
5249
// Server error (500)
53-
return new BaseResponse<string>()
54-
{
55-
Description = $"{TryRegister} : {ex.Message}",
56-
StatusCode = StatusCodes.InternalServerError,
57-
};
50+
return BaseResponse<string>.InternalServerError($"{TryRegister} : {ex.Message}");
5851
}
5952

6053
}
@@ -64,7 +57,7 @@ public async Task<IBaseResponse<string>> TryLogin(LoginUser form, string secretK
6457
// Hashing Password
6558
User user = _HashingServices.Hashing(form);
6659

67-
var baseResponse = new BaseResponse<string>();
60+
BaseResponse<string> baseResponse;
6861
try
6962
{
7063
// Find user email
@@ -77,35 +70,26 @@ public async Task<IBaseResponse<string>> TryLogin(LoginUser form, string secretK
7770
if (user.Password == userDb.Password)
7871
{
7972
// Ok (200)
80-
baseResponse.StatusCode = StatusCodes.Ok;
81-
// JWT token generate
82-
baseResponse.Data = _TokenServices.GenereteJWTToken(user, secretKey);
73+
baseResponse = BaseResponse<string>.Ok(data: _TokenServices.GenereteJWTToken(user, secretKey));
8374
}
8475
else
8576
{
86-
8777
// Unauthorized (401)
88-
baseResponse.StatusCode = StatusCodes.Unauthorized;
89-
baseResponse.Description = "Bad password";
78+
baseResponse = BaseResponse<string>.Unauthorized("Bad password");
9079
}
9180
}
9281
// User not exists
9382
else
9483
{
9584
// Unauthorized (401)
96-
baseResponse.StatusCode = StatusCodes.Unauthorized;
97-
baseResponse.Description = "Email not found";
85+
baseResponse = BaseResponse<string>.Unauthorized("Email not found");
9886
}
9987
return baseResponse;
10088
}
10189
catch (Exception ex)
10290
{
10391
// Server error (500)
104-
return new BaseResponse<string>()
105-
{
106-
Description = $"{TryRegister} : {ex.Message}",
107-
StatusCode = StatusCodes.InternalServerError,
108-
};
92+
return BaseResponse<string>.InternalServerError($"{TryLogin} : {ex.Message}");
10993
}
11094

11195
}

Services/Implementations/TokenServices.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ public class TokenServices : ITokenServices
1010
{
1111
public string GenereteJWTToken(User user, string secretKey)
1212
{
13-
var claims = new []
13+
var claims = new[]
1414
{
1515
new Claim(JwtRegisteredClaimNames.Sub, user.SecondName + user.FirstName),
1616
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),

0 commit comments

Comments
 (0)