bremen_short_url/BackEnd/api/validGoogleLogin.ashx

153 lines
4.6 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<%@ WebHandler Language="C#" Class="validGoogleLogin" %>
using System;
using System.Web;
using Google.Apis.Auth;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Services.Protocols;
using System.Security.Cryptography;
using System.Text;
using System.Web.SessionState;
using System.Data;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
public class validGoogleLogin : System.Web.HttpTaskAsyncHandler {
public override async System.Threading.Tasks.Task ProcessRequestAsync(HttpContext context) {
result objRet = new result();
DataContractJsonSerializer json = new DataContractJsonSerializer(objRet.GetType());
context.Response.ContentType = "application/json;charset=utf-8";
string jwt = (context.Request["jwt"] == null) ? "" : context.Request["jwt"].ToString();//回傳憑證
string remember = (context.Request["rem"] == null) ? "N" : context.Request["rem"].ToString();
if (jwt == "") {
objRet.ret = "no";
objRet.err_code = "0001";
objRet.message = "無JWT資料可以登入!";
json.WriteObject(context.Response.OutputStream, objRet);
return;
}
//validate it using Google.Apis.Auth (null if invalid)
//var validPayload = await GoogleJsonWebSignature.ValidateAsync(jwt);
GoogleJsonWebSignature.Payload payload = await ValidateGoogleTokenAsync(jwt);
if (payload == null) {
objRet.ret = "no";
objRet.err_code = "0002";
objRet.message = "JWT驗證失敗!";
json.WriteObject(context.Response.OutputStream, objRet);
return;
}
string googleID = System.Web.Configuration.WebConfigurationManager.AppSettings["googleOAuthID"].ToString();
string audience = payload.Audience.ToString();
if (audience != googleID) {
objRet.ret = "no";
objRet.err_code = "0003";
objRet.message = "JWT驗證失敗!";
json.WriteObject(context.Response.OutputStream, objRet);
return;
}
string userId = payload.Subject;
string email = payload.Email;
string name = payload.Name;
string user_sql = string.Format("select * from users where user_email = '{0}' and user_onjob = 'Y'", email);
autoBindDataTable objUser = new autoBindDataTable(user_sql);
if (objUser.dataRows.Count == 0) {
objRet.ret = "no";
objRet.err_code = "0004";
objRet.message = "無此Email帳號於PRM系統中請直屬主管加入!";
json.WriteObject(context.Response.OutputStream, objRet);
return;
}
string token_key = CreateRandomCode(36);
string user_uid = objUser.dataRows[0]["user_uid"].ToString();
string id = objUser.dataRows[0]["user_id"].ToString();
autoBindDataTable dataToken = new autoBindDataTable("select * from token where token_sn = -1");
DataRow rowToken = dataToken.newRow;
dataToken.dataRows.Add(rowToken);
rowToken["token_key"] = token_key;
rowToken["user_uid"] = user_uid;
rowToken["token_isremember"] = remember;
rowToken["token_expireddate"] = DateTime.Now.AddMinutes(60);
HttpCookie tokenCookie = new HttpCookie("token");
HttpCookie idCookie = new HttpCookie("id");
tokenCookie["token"] = token_key;
tokenCookie["uid"] = user_uid;
idCookie["id"] = id;
idCookie.Expires = DateTime.Now.AddDays(31);
if (remember == "Y") {
tokenCookie.Expires = DateTime.Now.AddDays(10);
rowToken["token_expireddate"] = DateTime.Now.AddDays(10);
}
dataToken.updateDataTable();
context.Response.Cookies.Add(tokenCookie);
context.Response.Cookies.Add(idCookie);
objRet.ret = "yes";
json.WriteObject(context.Response.OutputStream, objRet);
}
private static async Task<GoogleJsonWebSignature.Payload> ValidateGoogleTokenAsync(string idToken)
{
try
{
var payload = await GoogleJsonWebSignature.ValidateAsync(idToken);
if (payload == null || string.IsNullOrEmpty(payload.Email))
throw new UnauthorizedAccessException("Invalid Google Token");
return payload;
}
catch (Exception ex){
string exM = ex.Message;
throw new UnauthorizedAccessException("Invalid Google Token");
return null;
}
}
public string CreateRandomCode(int Number)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
Random rand = new Random(Guid.NewGuid().GetHashCode());
for (int i = 0; i <= Number - 1; i++)
{
int t = rand.Next(allCharArray.Length);
randomCode += allCharArray[t];
}
return randomCode;
}
public class result {
public string ret = "no";
public string err_code = "0000";
public string message = "";
}
public bool IsReusable {
get {
return false;
}
}
}