aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/Controllers/MyControllerBase.cs
blob: d4ee9d3e57ff2f3a1699308aba1090c8c87da5a7 (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
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using Timeline.Auth;
using Timeline.Models.Http;
using Timeline.Services.User;

namespace Timeline.Controllers
{
    public class MyControllerBase : ControllerBase
    {
        #region auth
        protected bool UserHasPermission(UserPermission permission)
        {
            return User.HasPermission(permission);
        }

        protected string? GetOptionalUsername()
        {
            return User.GetOptionalName();
        }

        protected string GetUsername()
        {
            return GetOptionalUsername() ?? throw new InvalidOperationException(Resource.ExceptionNoUsername);
        }

        protected long? GetOptionalUserId()
        {
            return User.GetOptionalUserId();
        }

        protected long GetUserId()
        {
            return GetOptionalUserId() ?? throw new InvalidOperationException(Resource.ExceptionNoUserId);
        }
        #endregion auth

        #region action result
        protected ObjectResult StatusCodeWithCommonResponse(int statusCode, int code, string message)
        {
            return StatusCode(statusCode, new CommonResponse(code, message));
        }

        protected ObjectResult OkWithCommonResponse(int statusCode = 0, string? message = null)
        {
            return Ok(new CommonResponse(statusCode, message ?? Resource.MessageOperationSucceeded));
        }

        protected ObjectResult OkWithCommonResponse(string? message)
        {
            return OkWithCommonResponse(message: message);
        }

        protected ObjectResult ForbidWithCommonResponse(string? message = null)
        {
            return StatusCode(StatusCodes.Status403Forbidden, new CommonResponse(ErrorCodes.Common.Forbid, message ?? Resource.MessageForbid));
        }

        protected ObjectResult ForbidWithCommonResponse(int code, string? message = null)
        {
            return StatusCode(StatusCodes.Status403Forbidden, new CommonResponse(code, message ?? Resource.MessageForbid));
        }

        protected ObjectResult DeleteWithCommonDeleteResponse(bool delete = true)
        {
            return StatusCode(StatusCodes.Status200OK, CommonDeleteResponse.Create(delete));
        }

        protected BadRequestObjectResult BadRequestWithCommonResponse(int code, string message)
        {
            return BadRequest(new CommonResponse(code, message));
        }
        #endregion action result
    }
}