OpenAuth.Net/OpenAuth.WebApi/Areas/SSO/Controllers/LoginController.cs

127 lines
3.6 KiB
C#
Raw Normal View History

2016-07-08 11:28:38 +08:00
using System;
using System.Web.Mvc;
using Newtonsoft.Json;
2016-07-11 18:21:26 +08:00
using OpenAuth.App;
2016-07-08 11:28:38 +08:00
using OpenAuth.App.SSO;
using OpenAuth.WebApi.Areas.SSO.Models;
using OpenAuth.WebApi.Areas.SSO.Models.Services;
namespace OpenAuth.WebApi.Areas.SSO.Controllers
{
/// <summary>
/// 公钥AppKey
/// 私钥AppSecret
/// 会话Token
/// </summary>
public class LoginController : Controller
{
private readonly AppInfoService _appInfoService = new AppInfoService();
2016-07-11 18:21:26 +08:00
private UserManagerApp _useraApp = AutofacExt.GetFromFac<UserManagerApp>();
2016-07-08 11:28:38 +08:00
private const string AppInfo = "AppInfo";
//默认登录界面
public ActionResult Index(string appKey = "", string username = "")
{
TempData[AppInfo] = _appInfoService.Get(appKey);
var viewModel = new PassportLoginRequest
{
AppKey = appKey,
UserName = username,
};
return View(viewModel);
}
//授权登录
[HttpPost]
public ActionResult Index(PassportLoginRequest model)
{
var result = Parse(model);
if (result.Success)
{
var redirectUrl = string.Format("{0}?token={1}&sessionusername={2}", result.ReturnUrl, result.Token, model.UserName);
//跳转默认回调页面
return Redirect(redirectUrl);
}
return View(model);
}
[HttpPost]
public string Check(PassportLoginRequest request)
{
return JsonConvert.SerializeObject(Parse(request));
}
[HttpPost]
public bool Logout(string token, string requestid)
{
try
{
new UserAuthSessionService().Remove(token);
return true;
}
catch (Exception)
{
return false;
}
}
private LoginResult Parse(PassportLoginRequest model)
{
//过滤字段无效字符
model.Trim();
var result = new LoginResult();
2016-07-11 18:21:26 +08:00
try
2016-07-08 11:28:38 +08:00
{
2016-07-11 18:21:26 +08:00
//获取应用信息
var appInfo = _appInfoService.Get(model.AppKey);
if (appInfo == null)
{
throw new Exception("应用不存在");
}
TempData[AppInfo] = appInfo;
//获取用户信息
var userInfo = _useraApp.Get(model.UserName);
if (userInfo == null)
{
throw new Exception("用户不存在");
}
if (userInfo.Password != model.Password)
{
throw new Exception("密码错误");
}
var currentSession = new UserAuthSession
{
UserName = model.UserName,
Token = Guid.NewGuid().ToString().ToMd5(),
InvalidTime = DateTime.Now.AddMinutes(10),
AppKey = model.AppKey,
CreateTime = DateTime.Now,
IpAddress = Request.UserHostAddress
};
//创建Session
new UserAuthSessionService().Create(currentSession);
result.Success = true;
result.ReturnUrl = appInfo.ReturnUrl;
result.Token = currentSession.Token;
2016-07-08 11:28:38 +08:00
}
2016-07-11 18:21:26 +08:00
catch (Exception ex)
2016-07-08 11:28:38 +08:00
{
result.Success = false;
2016-07-11 18:21:26 +08:00
result.ErrorMsg = ex.Message;
2016-07-08 11:28:38 +08:00
}
return result;
}
}
}