| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Linq; |
| | | 4 | | using System.Security.Claims; |
| | | 5 | | using System.Threading.Tasks; |
| | | 6 | | using CrmVtbc; |
| | | 7 | | using IdentityServer4.Extensions; |
| | | 8 | | using Microsoft.Extensions.Logging; |
| | | 9 | | using Microsoft.Extensions.Options; |
| | | 10 | | using SVETA.Api.Data.Domain; |
| | | 11 | | using SVETA.Api.Helpers.Authorize; |
| | | 12 | | using SVETA.Api.Services.Interfaces; |
| | | 13 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 14 | | using WinSolutions.Sveta.Server.Data.DataModel.Kinds; |
| | | 15 | | using WinSolutions.Sveta.Common; |
| | | 16 | | using Microsoft.AspNetCore.Http; |
| | | 17 | | using Microsoft.EntityFrameworkCore; |
| | | 18 | | using WinSolutions.Sveta.Server.Data.DataModel.Contexts; |
| | | 19 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 20 | | using Elasticsearch.Net.Specification.CatApi; |
| | | 21 | | using Microsoft.Extensions.Primitives; |
| | | 22 | | using Newtonsoft.Json; |
| | | 23 | | |
| | | 24 | | namespace SVETA.Api.Services.Implements |
| | | 25 | | { |
| | | 26 | | public class AuthenticationService : IAuthenticationService |
| | | 27 | | { |
| | | 28 | | User user; |
| | | 29 | | private User backUp; |
| | 0 | 30 | | public List<string> Roles { get; } |
| | | 31 | | //private readonly AuthenticationSettings _authenticationSettings; |
| | | 32 | | private readonly ConfigurationsSettings _confsSettings; |
| | | 33 | | private readonly SvetaDbContext _db; |
| | | 34 | | private readonly ICommonUserService _commonUserService; |
| | | 35 | | private readonly IHttpContextAccessor _context; |
| | | 36 | | private readonly ICrmSyncWorker _crmSyncWorker; |
| | 0 | 37 | | private string svetaDDistr = "svetaDDistr"; |
| | | 38 | | private readonly bool hasCompany; |
| | | 39 | | private readonly bool hasUser; |
| | | 40 | | private readonly bool hasScope; |
| | | 41 | | private readonly bool hasConfirmed; |
| | 0 | 42 | | private readonly int confirmed = 0; |
| | | 43 | | private Guid companyTid; |
| | | 44 | | private Guid userTid; |
| | | 45 | | private Guid anonymUser; |
| | | 46 | | private Guid serviceUser; |
| | | 47 | | private Guid anonymousUuid; |
| | | 48 | | |
| | 0 | 49 | | public AuthenticationService(IHttpContextAccessor context, SvetaDbContext db, ICommonUserService commonUserServi |
| | 0 | 50 | | ILogger<AuthenticationService> logger, IOptions<AuthenticationSettings> options, IOptions<ConfigurationsSett |
| | 0 | 51 | | { |
| | | 52 | | try |
| | 0 | 53 | | { |
| | 0 | 54 | | _db = db; |
| | 0 | 55 | | _context = context; |
| | 0 | 56 | | _confsSettings = optionsConf.Value; |
| | 0 | 57 | | _commonUserService = commonUserService; |
| | | 58 | | //_authenticationSettings = options.Value; |
| | 0 | 59 | | _crmSyncWorker = crmSyncWorker; |
| | 0 | 60 | | Roles = new List<string>(); |
| | 0 | 61 | | if (!Guid.TryParse(_confsSettings.GetConfValue("AuthenticationSettings", "AnonymUserTID"), out anonymUse |
| | 0 | 62 | | throw new ArgumentException("Не удалось разобрать значение ключа AnonymUserTID в секции Authenticati |
| | 0 | 63 | | if (!Guid.TryParse(_confsSettings.GetConfValue("AuthenticationSettings", "ServiceUserTID"), out serviceU |
| | 0 | 64 | | throw new ArgumentException("Не удалось разобрать значение ключа ServiceUserTID в секции Authenticat |
| | | 65 | | |
| | | 66 | | StringValues anonymStringKey; |
| | 0 | 67 | | if (context?.HttpContext?.Request?.Headers?.Keys?.Contains("Anonymous-UUID", StringComparer.OrdinalIgnor |
| | 0 | 68 | | { |
| | 0 | 69 | | if (context?.HttpContext?.Request?.Headers?.TryGetValue("Anonymous-UUID", out anonymStringKey) ?? fa |
| | 0 | 70 | | { |
| | 0 | 71 | | Guid.TryParse(anonymStringKey, out anonymousUuid); |
| | 0 | 72 | | } |
| | 0 | 73 | | } |
| | | 74 | | |
| | 0 | 75 | | if (context?.HttpContext?.User != null) |
| | 0 | 76 | | { |
| | 0 | 77 | | var userClaims = context.HttpContext.User.Claims.IsNullOrEmpty() ? CreateClaims(anonymUser) : contex |
| | 0 | 78 | | Roles = userClaims.Claims.Where(claim => claim.Type.Contains("role", StringComparison.OrdinalIgnoreC |
| | 0 | 79 | | .Select(claim => claim.Value).ToList(); |
| | 0 | 80 | | var dd_roles = _commonUserService.GetRoles().Result; |
| | 0 | 81 | | if (!Roles.Any(x => dd_roles.Any(e => e.Name == x))) |
| | 0 | 82 | | Roles.Add(Role.Anonym); |
| | 0 | 83 | | hasCompany = Guid.TryParse(userClaims.Claims.FirstOrDefault(claim => claim.Type.Contains("company_TI |
| | 0 | 84 | | .Value, out companyTid); |
| | 0 | 85 | | if (!hasCompany) |
| | 0 | 86 | | { |
| | 0 | 87 | | logger.LogError("Отсутствует company_TID в context claims"); |
| | | 88 | | //logger.LogError(JsonConvert.SerializeObject(userClaims.Claims.)); |
| | 0 | 89 | | throw new ForbidException("В токене отсутствует company_TID"); |
| | | 90 | | } |
| | 0 | 91 | | hasUser = Guid.TryParse(userClaims.Claims.FirstOrDefault(claim => claim.Type.Contains("user_TID"))? |
| | 0 | 92 | | .Value, out userTid); |
| | 0 | 93 | | if (!hasUser) |
| | 0 | 94 | | { |
| | 0 | 95 | | logger.LogError("Отсутствует user_TID в context claims"); |
| | | 96 | | //logger.LogError(JsonConvert.SerializeObject(userClaims.Claims)); |
| | 0 | 97 | | throw new ForbidException("В токене отсутствует user_TID"); |
| | | 98 | | } |
| | 0 | 99 | | hasScope = userClaims.Claims.Where(claim => claim.Type.Contains("scope")) |
| | 0 | 100 | | .Any(claim => claim.Value.Equals(svetaDDistr, StringComparison.Ordinal)); |
| | 0 | 101 | | if (!hasScope) |
| | 0 | 102 | | { |
| | 0 | 103 | | logger.LogError("Отсутствует scope ddistr в context claims"); |
| | | 104 | | //logger.LogError(JsonConvert.SerializeObject(context.HttpContext)); |
| | 0 | 105 | | throw new UnauthorizedAccessException(); |
| | | 106 | | } |
| | 0 | 107 | | hasConfirmed = userClaims.Claims.Any(claim => claim.Type.Contains("confirmed")); |
| | 0 | 108 | | confirmed = hasConfirmed ? Int32.Parse(userClaims.Claims.FirstOrDefault(claim => claim.Type.Contains |
| | 0 | 109 | | CreateUser(userClaims); |
| | 0 | 110 | | } |
| | 0 | 111 | | } |
| | 0 | 112 | | catch (Exception e) |
| | 0 | 113 | | { |
| | 0 | 114 | | Console.WriteLine(e); |
| | 0 | 115 | | throw; |
| | | 116 | | } |
| | | 117 | | |
| | 0 | 118 | | } |
| | | 119 | | |
| | | 120 | | /// <summary> |
| | | 121 | | /// Создает сессию пользователя с указанным набором клаймсов |
| | | 122 | | /// </summary> |
| | | 123 | | /// <param name="claims">набор клаймсов</param> |
| | | 124 | | void CreateUser(ClaimsPrincipal claims) |
| | 0 | 125 | | { |
| | 0 | 126 | | userTid = claims.Claims.GetUserTID(); |
| | 0 | 127 | | companyTid = claims.Claims.GetCompanyTID(); |
| | | 128 | | try |
| | 0 | 129 | | { |
| | 0 | 130 | | if (_context?.HttpContext?.Request.Path.Value.ToLower().EndsWith("whoami") == true && userTid != anonymU |
| | 0 | 131 | | && userTid != serviceUser) |
| | 0 | 132 | | _crmSyncWorker.SyncWithCrm(userTid, companyTid).Wait(); |
| | 0 | 133 | | } |
| | 0 | 134 | | catch (AggregateException ae) |
| | 0 | 135 | | { |
| | 0 | 136 | | if (ae.InnerException is SvetaException) |
| | 0 | 137 | | throw new SvetaException($"Возникла ошибка при синхронизации с CRM. {ae.InnerException.Message}", (a |
| | 0 | 138 | | throw new SvetaException($"Возникла неизвестная ошибка при синхронизации с CRM. {ae.Message}", (int)Erro |
| | | 139 | | } |
| | | 140 | | |
| | 0 | 141 | | user = _commonUserService.GetUser(userTid).Result; |
| | 0 | 142 | | if (user == null) |
| | 0 | 143 | | { |
| | 0 | 144 | | throw new ForbidException("Пользователь не найден."); |
| | | 145 | | } |
| | 0 | 146 | | } |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// Создает набор клаймсов для сервисного/анонимного пользователей |
| | | 150 | | /// </summary> |
| | | 151 | | /// <param name="tid">Гуид пользователя</param> |
| | | 152 | | /// <returns></returns> |
| | | 153 | | private ClaimsPrincipal CreateClaims(Guid tid) |
| | 0 | 154 | | { |
| | 0 | 155 | | var claims = new List<Claim> |
| | 0 | 156 | | { |
| | 0 | 157 | | new Claim("user_TID", tid.ToString()), |
| | 0 | 158 | | new Claim("scope", svetaDDistr) |
| | 0 | 159 | | }; |
| | 0 | 160 | | if (tid == anonymUser) |
| | 0 | 161 | | { |
| | 0 | 162 | | claims.Add(new Claim("role", Role.Anonym)); |
| | 0 | 163 | | claims.Add(new Claim("company_TID", Guid.NewGuid().ToString())); |
| | 0 | 164 | | claims.Add(new Claim("confirmed", "1")); |
| | 0 | 165 | | } |
| | 0 | 166 | | ClaimsIdentity id = new ClaimsIdentity(claims); |
| | 0 | 167 | | return new ClaimsPrincipal(id); |
| | 0 | 168 | | } |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// Возвращает GUID анонимного пользователя |
| | | 172 | | /// </summary> |
| | | 173 | | /// <returns></returns> |
| | | 174 | | public Guid AnonymousUuid |
| | | 175 | | { |
| | 0 | 176 | | get => anonymousUuid; |
| | | 177 | | } |
| | | 178 | | |
| | | 179 | | /// <summary> |
| | | 180 | | /// Id текущего пользователя |
| | | 181 | | /// </summary> |
| | 0 | 182 | | public long UserId => user.Id; |
| | | 183 | | |
| | | 184 | | /// <summary> |
| | | 185 | | /// Почта текущего пользователя |
| | | 186 | | /// </summary> |
| | 0 | 187 | | public string UserEmail => user.Email; |
| | | 188 | | |
| | | 189 | | /// <summary> |
| | | 190 | | /// Id контрагента |
| | | 191 | | /// </summary> |
| | 0 | 192 | | public long ContragentId => user.Contragent.Id; |
| | | 193 | | |
| | | 194 | | /// <summary> |
| | | 195 | | /// Тип контрагента |
| | | 196 | | /// </summary> |
| | 0 | 197 | | public long ContragentKindId => user.Contragent.ContragentsKind.Id; |
| | | 198 | | |
| | | 199 | | /// <summary> |
| | | 200 | | /// Переключает в контекст технического пользователя |
| | | 201 | | /// </summary> |
| | | 202 | | public void SwitchToServiceUser() |
| | 0 | 203 | | { |
| | 0 | 204 | | backUp = user; |
| | 0 | 205 | | CreateUser(CreateClaims(serviceUser)); |
| | 0 | 206 | | } |
| | | 207 | | |
| | | 208 | | /// <summary> |
| | | 209 | | /// Возвращает контекст сохраненного пользователя перед переключением |
| | | 210 | | /// </summary> |
| | 0 | 211 | | public void RevertUser() => user = backUp; |
| | | 212 | | |
| | | 213 | | /// <summary> |
| | | 214 | | /// Переключает в контекст анонимного пользователя |
| | | 215 | | /// </summary> |
| | 0 | 216 | | public void SwitchToAnonymous() => CreateUser((CreateClaims((anonymUser)))); |
| | | 217 | | |
| | | 218 | | /// <summary> |
| | | 219 | | /// Проверяет, является ли пользователем владельцем контрагента |
| | | 220 | | /// </summary> |
| | | 221 | | /// <returns></returns> |
| | 0 | 222 | | public bool IsOwner() => user.Contragent?.Owner.Id == user.Id; |
| | | 223 | | |
| | | 224 | | /// <summary> |
| | | 225 | | /// Проверяет, что контрагент авторизованного пользователя относится к группе Поставщики |
| | | 226 | | /// </summary> |
| | | 227 | | /// <returns>bool</returns> |
| | 0 | 228 | | public bool IsUserWholesaler() => user.Contragent.ContragentsKind.Id == (long)ContragentKind.Wholesaler; |
| | | 229 | | |
| | | 230 | | /// <summary> |
| | | 231 | | /// Проверяет, что контрагент авторизованного пользователя относится к группе Магазины |
| | | 232 | | /// </summary> |
| | | 233 | | /// <returns>bool</returns> |
| | 0 | 234 | | public bool IsUserRetailer() => user.Contragent.ContragentsKind.Id == (long)ContragentKind.Retailer; |
| | | 235 | | |
| | | 236 | | /// <summary> |
| | | 237 | | /// Проверяет, что контрагент авторизованного пользователя относится к группе Производители |
| | | 238 | | /// </summary> |
| | | 239 | | /// <returns>bool</returns> |
| | 0 | 240 | | public bool IsUserManufacturer() => user.Contragent.ContragentsKind.Id == (long)ContragentKind.Manufacturer; |
| | | 241 | | |
| | | 242 | | /// <summary> |
| | | 243 | | /// Проверяет, что контрагент авторизованного пользователя относится к группе Платформа |
| | | 244 | | /// </summary> |
| | | 245 | | /// <returns>bool</returns> |
| | 0 | 246 | | public bool IsUserPlatform() => user.Contragent.ContragentsKind.Id == (long)ContragentKind.Platform; |
| | | 247 | | |
| | | 248 | | /// <summary> |
| | | 249 | | /// Пользователь подтвердил почту или телефон в ЦРМ |
| | | 250 | | /// </summary> |
| | | 251 | | /// <returns></returns> |
| | 0 | 252 | | public bool Confirmed() => hasConfirmed && confirmed == 1; |
| | | 253 | | |
| | | 254 | | /// <summary> |
| | | 255 | | /// Пользователь подтвердил данные в ЦРМ и получил userTID |
| | | 256 | | /// </summary> |
| | | 257 | | /// <returns></returns> |
| | 0 | 258 | | public bool Register() => hasConfirmed && confirmed == 1 && !userTid.IsDefaultValueOrNull(); |
| | | 259 | | |
| | | 260 | | /// <summary> |
| | | 261 | | /// Пользователь имеет прописанный companyTID |
| | | 262 | | /// </summary> |
| | | 263 | | /// <returns></returns> |
| | 0 | 264 | | public bool CompanyAssigned() => !companyTid.IsDefaultValueOrNull(); |
| | | 265 | | |
| | | 266 | | /// <summary> |
| | | 267 | | /// Проверяет авторизован ли текущий пользователь |
| | | 268 | | /// </summary> |
| | | 269 | | /// <returns></returns> |
| | 0 | 270 | | public bool IsAnonym() => user.ExternalKey.Equals(anonymUser); |
| | | 271 | | } |
| | | 272 | | } |