using cylsg.Authorization;
using cylsg.Core;
using cylsg.Model.UserModel;
using cylsg.utility.Extend;
using EzWechat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cylsg.Application
{
///
/// 登录
///
[DynamicApiController]
[ApiDescriptionSettings("Default@1")]
public class LogoIn
{
private readonly IWechatService _wechatService;
private readonly IEzAuthorizationService _ezAuthorizationService;
public LogoIn(IWechatService wechatService,
IEzAuthorizationService ezAuthorizationService)
{
_wechatService = wechatService;
_ezAuthorizationService = ezAuthorizationService;
}
///
/// 快速登录
///
///
[HttpGet]
[QueryParameters]
public async Task LogoinFast(string jscode)
{
var opeid = await _wechatService.GetOpenID(jscode);
var UserRes = new BaseRepository();
var user = await UserRes.GetFirstAsync(x => x.WxOpenId == opeid);
if (user == null)
{
throw Oops.Oh("没找到用户,需要重新注册登录");
}
var jwt = new EzJwtModel()
{
//ITCode = user.ItCode, 不在明文中使用Itcode
NickName = user.Nickname,
UserID = user.Id,
};
return _ezAuthorizationService.CreateToken(jwt);
}
///
/// 注册用户并登录
///
/// logoinjscode
///
[HttpPost]
public async Task CreateUser(UserInfoIn Param)
{
var opeid = await _wechatService.GetOpenID(Param.JsCode);
var UserRes = new BaseRepository();
var user = await UserRes.GetFirstAsync(x => x.WxOpenId == opeid);
if (user == null)
{
//没有用户 ,需要新建用户
var phone = await _wechatService.GetPhone(Param.Bindgetphonenumber);
user = await UserRes.GetFirstAsync(x => x.ItCode == phone);
if(user == null) {
user = new User
{
Avatar = phone,
Nickname = Param.Nickname??phone.PrivacyStr(),
name = Param.Name ?? phone,
Phone = phone,
ItCode = phone,
PassWord = "123456",
WxOpenId = opeid,
CreateBy="微信注册登录",
CreateTime = DateTime.UtcNow,
};
user= await UserRes.InsertReturnEntityAsync(user);
}
else
{
user.WxOpenId = opeid;
await UserRes.EzUpdateAsync(user);
}
}
var jwt = new EzJwtModel()
{
// ITCode = user.ItCode,
NickName = user.Nickname,
UserID = user.Id,
};
return _ezAuthorizationService.CreateToken(jwt);
}
}
///
/// 创建用户模型
///
public class UserInfoIn()
{
///
/// 头像
///
public string? Avatar { get; set; }
///
/// 昵称
///
public string? Nickname { get; set; }
///
/// 电话
///
public string? Phone { get; set; }
///
/// 名称
///
public string? Name { get; set; }
///
/// 手机号换取码
///
[Required]
public string Bindgetphonenumber { get; set; }
///
/// jscode
///
[Required]
public string JsCode { get; set;}
}
}