using IdentityModel.Client;
using log4net.ObjectRenderer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using Shentun.Peis.Models;
using Shentun.Peis.MyUser;
using Shentun.Peis.OrganizationUnits;
using Shentun.Peis.Permissions;
using Shentun.Peis.RegisterCheckPictures;
using Shentun.Peis.Sexs;
using Shentun.Utilities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Account;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity;
using Volo.Abp.ObjectExtending;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Security.Encryption;
using Volo.Abp.Users;
namespace Shentun.Peis.MyUser
{
///
/// 重写IdentityUser服务
///
[Dependency(ReplaceServices = true)]
////[RemoteService(isEnabled: false)]
[ExposeServices(typeof(IIdentityUserAppService))]
public class MyUserAppService : IdentityUserAppService
{
private readonly IRepository _identityUserRepository;
private readonly IdentityUserManager _userManager;
private readonly IIdentityUserRepository _userRepository;
private readonly IOptions _identityOptions;
private readonly IPasswordHasher _passwordHasher;
private readonly IStringEncryptionService _stringEncryptionService;
private readonly PeisOrganizationUnitManager _peisOrganizationUnitManager;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
private readonly IRepository _organizationUnitRepository;
private readonly IRepository _identityUserOrganizationUnitRepository;
private readonly CurrentUser _currentUser;
private readonly IDistributedCache _userCache;
public MyUserAppService(
IRepository identityUserRepository,
IdentityUserManager userManager,
IIdentityUserRepository userRepository,
IIdentityRoleRepository roleRepository,
IOptions identityOptions,
IPasswordHasher passwordHasher,
IStringEncryptionService stringEncryptionService,
IRepository organizationUnitRepository,
PeisOrganizationUnitManager peisOrganizationUnitManager,
IHttpClientFactory httpClientFactory,
IConfiguration configuration,
IRepository identityUserOrganizationUnitRepository,
CurrentUser currentUser,
IDistributedCache userCache) :
base(userManager,
userRepository,
roleRepository,
identityOptions)
{
this._identityUserRepository = identityUserRepository;
this._userManager = userManager;
this._userRepository = userRepository;
this._identityOptions = identityOptions;
this._passwordHasher = passwordHasher;
this._stringEncryptionService = stringEncryptionService;
this._peisOrganizationUnitManager = peisOrganizationUnitManager;
this._httpClientFactory = httpClientFactory;
this._configuration = configuration;
this._organizationUnitRepository = organizationUnitRepository;
this._identityUserOrganizationUnitRepository = identityUserOrganizationUnitRepository;
this._currentUser = currentUser;
_userCache = userCache;
}
///
/// 根据角色查询用户列表
///
///
///
[Authorize(PeisPermissions.Users.Default)]
[HttpGet("api/identity/users/userlistbyrolename")]
public async Task> GetUserListByRoleName(string RoleName)
{
var userlist = await _userRepository.GetListByNormalizedRoleNameAsync(RoleName);
return ObjectMapper.Map, List>(userlist);
}
///
/// 修改用户密码 修改自身密码
///
///
///
[Authorize(PeisPermissions.Users.Default)]
[HttpPost("api/identity/users/updatepassword")]
public async Task UpdatePassWordAsync(UpdatePasswordDto input)
{
var user = await _userManager.FindByIdAsync(_currentUser.Id.ToString());
if (user != null)
{
var isPassWord = await _userManager.CheckPasswordAsync(user, input.OldPassWord);
if (!isPassWord)
{
throw new UserFriendlyException("原密码不正确");
}
await _userManager.RemovePasswordAsync(user);
await _userManager.AddPasswordAsync(user, input.NewPassWord);
}
}
///
/// 管理员重置用户密码
///
///
///
[Authorize(PeisPermissions.Users.Default)]
[HttpPost("api/identity/users/resetpassword")]
public async Task ResetPassWordAsync(ResetPassWordDto input)
{
var user = await _userManager.FindByIdAsync(input.UserId.ToString());
if (user != null)
{
var RemoveMsg = await _userManager.RemovePasswordAsync(user);
if (!RemoveMsg.Succeeded)
throw new UserFriendlyException($"操作失败,{RemoveMsg.Errors.FirstOrDefault().Code}");
var AddPasswordMsg = await _userManager.AddPasswordAsync(user, input.NewPassWord);
if (!AddPasswordMsg.Succeeded)
throw new UserFriendlyException($"操作失败,{AddPasswordMsg.Errors.FirstOrDefault().Code}");
}
}
/////
///// 创建
/////
/////
/////
//[Authorize(PeisPermissions.Users.Create)]
//[HttpPost("api/identity/users/create")]
//public override Task CreateAsync(IdentityUserCreateDto input)
//{
// return base.CreateAsync(input);
//}
///
/// 创建 可以不带邮箱 自动以用户名生成
///
///
///
[Authorize(PeisPermissions.Users.Create)]
[HttpPost("api/identity/users/create")]
public async Task CreateAsync(IdentityUserCreateNoEmailDto input)
{
#region 上传图片
string userPhoto = UploadUserPhotoAsync(new UploadUserPhotoInputDto { PictureBaseStr = input.UserPhoto });
string userSign = UploadUserSignAsync(new UploadUserPhotoInputDto { PictureBaseStr = input.UserSign });
#endregion
IdentityUserCreateDto newinput = new IdentityUserCreateDto
{
Email = string.IsNullOrWhiteSpace(input.Email) ? input.UserName + "@qq.com" : input.Email,
IsActive = input.IsActive,
LockoutEnabled = input.LockoutEnabled,
Name = input.Name,
Password = input.Password,
PhoneNumber = input.PhoneNumber,
RoleNames = input.RoleNames,
Surname = input.Surname,
UserName = input.UserName
};
await IdentityOptions.SetAsync();
var user = new IdentityUser(
GuidGenerator.Create(),
newinput.UserName,
newinput.Email,
CurrentTenant.Id
);
user.SetProperty("user_photo", userPhoto);
user.SetProperty("user_sign", userSign);
user.SetProperty("operator_type", input.OperatorType);
newinput.MapExtraPropertiesTo(user);
(await UserManager.CreateAsync(user, input.Password)).CheckErrors();
await UpdateUserByInput(user, newinput);
(await UserManager.UpdateAsync(user)).CheckErrors();
await CurrentUnitOfWork.SaveChangesAsync();
var entityDto = ObjectMapper.Map(user);
var entity = await _identityUserRepository.GetAsync(entityDto.Id);
_userCache.Set(entityDto.Id, entity);
return entityDto;
}
///
/// 删除用户
///
///
///
[Authorize(PeisPermissions.Users.Delete)]
[HttpPost("api/identity/users/delete")]
public override Task DeleteAsync(Guid id)
{
return base.DeleteAsync(id);
}
///
/// 获取列表
///
///
///
[Authorize(PeisPermissions.Users.Default)]
[HttpGet("api/identity/users/getlist")]
public override Task> GetListAsync(GetIdentityUsersInput input)
{
return base.GetListAsync(input);
}
///
/// 获取列表 根据科室查询 不传科室查所有
///
///
///
[Authorize(PeisPermissions.Users.Default)]
[HttpPost("api/identity/users/getlistinorganizationunit")]
public async Task> GetListInOrganizationUnitAsync(OrganizationUnitIdIuputDto input)
{
List userList = new List();
var identityUserOrganizationUnitList = await _identityUserOrganizationUnitRepository.GetListAsync();
if (input.OrganizationUnitId != null && input.OrganizationUnitId != Guid.Empty)
{
List organizationUnitIds = await _peisOrganizationUnitManager.GetOrganizationUnitChildIds(input.OrganizationUnitId.Value);
userList = await _userRepository.GetUsersInOrganizationsListAsync(organizationUnitIds);
}
else
{
userList = await _identityUserRepository.GetListAsync(m => m.IsDeleted == false);
}
var entlistdto = userList.Select(s => new IdentityUserWithExtensionDto
{
UserSign = s.GetProperty("user_sign"),
UserPhoto = s.GetProperty("user_photo"),
OperatorType = s.GetProperty("operator_type"),
ConcurrencyStamp = s.ConcurrencyStamp,
CreationTime = s.CreationTime,
CreatorId = s.CreatorId,
DeleterId = s.DeleterId,
DeletionTime = s.DeletionTime,
Email = s.Email,
EmailConfirmed = s.EmailConfirmed,
Id = s.Id,
IsActive = s.IsActive,
IsDeleted = s.IsDeleted,
LastModificationTime = s.LastModificationTime,
LastModifierId = s.LastModifierId,
LockoutEnabled = s.LockoutEnabled,
LockoutEnd = s.LockoutEnd,
Name = s.Name,
PhoneNumber = s.PhoneNumber,
PhoneNumberConfirmed = s.PhoneNumberConfirmed,
Surname = s.Surname,
TenantId = s.TenantId,
UserName = s.UserName,
//OrganizationUnitId = identityUserOrganizationUnitList.FirstOrDefault(m => m.UserId == s.Id) != null? identityUserOrganizationUnitList.FirstOrDefault(m => m.UserId == s.Id).OrganizationUnitId:Guid.Empty,
OrganizationUnitId = identityUserOrganizationUnitList.FirstOrDefault(m => m.UserId == s.Id)?.OrganizationUnitId,
SimpleCode = LanguageConverter.GetPYSimpleCode(s.Surname)
}).ToList();
// var entlistdto = ObjectMapper.Map, List>(entlist);
return entlistdto;
}
///
/// 获取列表 根据用户类别
///
///
///
[Authorize(PeisPermissions.Users.Default)]
[HttpPost("api/identity/users/GetListByOperatorType")]
public async Task> GetListByOperatorTypeAsync(OperatorTypeIuputDto input)
{
var entlist = await _identityUserRepository.GetListAsync(m => m.IsDeleted == false);
var entlistDto = entlist.Where(m => input.OperatorTypes.Contains(m.GetProperty("operator_type"))).Select(s => new ListByOperatorTypeDto
{
Id = s.Id,
SimpleCode = LanguageConverter.GetPYSimpleCode(s.Surname),
Surname = s.Surname,
UserName = s.UserName
}).ToList();
return entlistDto;
}
///
/// 修改用户信息
///
///
///
///
//[Authorize(PeisPermissions.Users.Edit)]
//[HttpPost("api/identity/users/update")]
[RemoteService(false)]
public override async Task UpdateAsync(Guid id, IdentityUserUpdateDto input)
{
var entityDto = await base.UpdateAsync(id, input);
var entity = await _identityUserRepository.GetAsync(id);
_userCache.Set(id, entity);
return entityDto;
}
///
/// 修改
///
///
///
///
[Authorize(PeisPermissions.Users.Edit)]
[HttpPost("api/identity/users/update")]
public async Task UpdateIdentityUserAsync(Guid id, IdentityUserUpdateInputDto input)
{
#region 上传图片
string userPhoto = UploadUserPhotoAsync(new UploadUserPhotoInputDto
{
PictureBaseStr = input.UserPhoto,
UserId = id
});
string userSign = UploadUserSignAsync(new UploadUserPhotoInputDto
{
PictureBaseStr = input.UserSign,
UserId = id
});
#endregion
input.Email = input.UserName + "@qq.com";
await IdentityOptions.SetAsync();
var user = await UserManager.GetByIdAsync(id);
user.SetProperty("user_sign", userSign);
user.SetProperty("user_photo", userPhoto);
user.SetProperty("operator_type", input.OperatorType);
user.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp);
(await UserManager.SetUserNameAsync(user, input.UserName)).CheckErrors();
await UpdateUserByInput(user, input);
input.MapExtraPropertiesTo(user);
(await UserManager.UpdateAsync(user)).CheckErrors();
if (!input.Password.IsNullOrEmpty())
{
(await UserManager.RemovePasswordAsync(user)).CheckErrors();
(await UserManager.AddPasswordAsync(user, input.Password)).CheckErrors();
}
await CurrentUnitOfWork.SaveChangesAsync();
var entityDto = ObjectMapper.Map(user);
var entity = await _identityUserRepository.GetAsync(id);
_userCache.Set(id, entity);
return entityDto;
}
///
/// 获取用户信息 根据ID
///
///
///
//[Authorize(PeisPermissions.Users.Default)]
//[HttpGet("api/identity/users/getinfo")]
[RemoteService(false)]
public override Task GetAsync(Guid id)
{
return base.GetAsync(id);
}
///
///上传用户照片 图片base64
///
///
///
///
private string UploadUserPhotoAsync(UploadUserPhotoInputDto input)
{
string fileName = "";
if (input.UserId != null)
{
fileName = input.UserId.ToString();
}
else
{
fileName = Guid.NewGuid().ToString();
}
string imgurl = $"UserPhoto/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/{fileName}";
var isupload = ImageHelper.Base64StrToImage(input.PictureBaseStr, imgurl);
if (!string.IsNullOrEmpty(isupload))
return isupload;
else
return "";
}
///
/// 上传用户签名 图片base64
///
///
///
///
private string UploadUserSignAsync(UploadUserPhotoInputDto input)
{
string fileName = "";
if (input.UserId != null)
{
fileName = input.UserId.ToString();
}
else
{
fileName = Guid.NewGuid().ToString();
}
string imgurl = $"UserSign/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/{fileName}";
var isupload = ImageHelper.Base64StrToImage(input.PictureBaseStr, imgurl);
if (!string.IsNullOrEmpty(isupload))
return isupload;
else
return "";
}
///
/// 获取用户信息 根据ID
///
///
///
[Authorize(PeisPermissions.Users.Default)]
[HttpGet("api/identity/users/getinfo")]
public async Task GetWithExtensionAsync(Guid id)
{
var ent = await UserManager.GetByIdAsync(id);
var userSign = !string.IsNullOrWhiteSpace(ent.GetProperty("user_sign")) ? ImageHelper.GetImageBase64StringAsync(ent.GetProperty("user_sign")) : "";
var userPhoto = !string.IsNullOrWhiteSpace(ent.GetProperty("user_photo")) ? ImageHelper.GetImageBase64StringAsync(ent.GetProperty("user_photo")) : "";
var operatorType = ent.GetProperty("operator_type");
var entDto = ObjectMapper.Map(ent);
entDto.UserPhoto = userPhoto;
entDto.UserSign = userSign;
entDto.OperatorType = operatorType;
return entDto;
}
///
/// 给用户绑定角色
///
/// 用户ID
/// 角色集合
///
[Authorize(PeisPermissions.Users.Edit)]
[HttpPost("api/identity/users/updateroles")]
public override Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input)
{
return base.UpdateRolesAsync(id, input);
}
///
/// 获取用户的角色信息 根据用户ID
///
/// 用户ID
///
[Authorize(PeisPermissions.Users.Default)]
[HttpGet("api/identity/users/getroles")]
public override Task> GetRolesAsync(Guid id)
{
return base.GetRolesAsync(id);
}
///
/// 获取当前登录用户的角色信息
///
///
[Authorize(PeisPermissions.Users.Default)]
[HttpGet("api/identity/users/getassignableroles")]
public override Task> GetAssignableRolesAsync()
{
return base.GetAssignableRolesAsync();
}
///
/// 暂未用到
///
///
///
[Authorize(PeisPermissions.Users.Default)]
[RemoteService(false)]
public override Task FindByUsernameAsync(string userName)
{
return base.FindByUsernameAsync(userName);
}
///
/// 暂未用到
///
///
///
[Authorize(PeisPermissions.Users.Default)]
[RemoteService(false)]
public override Task FindByEmailAsync(string email)
{
return base.FindByEmailAsync(email);
}
///
/// 用户登录
///
///
///
[HttpPost("api/identity/users/login")]
public async Task UserLogin(UserLoginRequestDto input)
{
UserLoginDto msg;
var user = await _userManager.FindByNameAsync(input.UserName);
if (user != null)
{
var verifyResult = await _userManager.CheckPasswordAsync(user, input.PassWord);
if (verifyResult)
{
var PeisId = await _peisOrganizationUnitManager.GetPeisIdAsync(user.Id);
if (user.IsActive == false)
{
throw new UserFriendlyException("账号已被禁用");
}
if (user.LockoutEnabled == true)
{
throw new UserFriendlyException("账号已被锁定");
}
TokenResponse token = await RequestAuthServerLoginByPasswordAsync(input.UserName, input.PassWord);
if (token.HttpResponse != null && token.HttpResponse.StatusCode == HttpStatusCode.OK)
{
msg = new UserLoginDto
{
//code = 1,
//msg = "登录成功",
peisid = PeisId,
UserId = user.Id,
OperatorType = user.GetProperty("operator_type"),
access_token = token.AccessToken,
expires_in = token.ExpiresIn,
refresh_token = token.RefreshToken,
token_type = token.TokenType
};
}
else
{
//msg = new UserLoginDto { code = 1, msg = "登录成功", peisid = PeisId };
throw new UserFriendlyException("获取token失败");
}
}
else
{
//msg = new UserLoginDto { code = -1, msg = "密码不正确" };
throw new UserFriendlyException("密码不正确");
}
#region MyRegion
//var verifyResult = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, PassWord);
//if (verifyResult == PasswordVerificationResult.Success)
//{
// return "1";
//}
//else
//{
// throw new UserFriendlyException("密码错误");
//}
#endregion
}
else
{
//msg = new UserLoginDto { code = -1, msg = "用户不存在" };
throw new UserFriendlyException("用户不存在");
}
return msg;
}
protected virtual async Task RequestAuthServerLoginByPasswordAsync(string username, string password)
{
var client = _httpClientFactory.CreateClient();
var request = new PasswordTokenRequest
{
Address = _configuration["AuthServer:Authority"] + "/connect/token",
//GrantType = "password",
//UserName = username,
//Password = password,
//Scope = "Peis offline_access",
//ClientId = "Peis_App",
Parameters =
{
{"username",username},
{"password",password },
{"scope","Peis offline_access" },
{"client_id","Peis_App" },
{"grant_type","password" }
}
};
//request.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
return await client.RequestTokenAsync(request);
}
}
}