// void cb_response(string from_jid, RequestToken token, string result, string options) { // 将工作线程转换到窗口线程 if (this.InvokeRequired) this.Invoke(guiResponse_, new object[] { from_jid, token, result, options }); else gui_response(from_jid, token, result, options); }
public string getAuthUrl() { // リクエスト トークンを生成 // reqToken = TwitterConsumer.ObtainUnauthorizedRequestToken("http://twitter.com/oauth/request_token", "http://twitter.com/"); // 認証ページのURLを返す // return Consumer.BuildUserAuthorizationURL("http://twitter.com/oauth/authorize", reqToken); }
/// <summary> /// Returns a URL that you can redirect the user to on the Evernote site that /// will prompt them to authroize your app. Once they do this, they will /// be redirected to callbackUri with the oauth_validator parameter /// </summary> /// <param name="callbackUri">The end point you plan on using to call ParseAccessToken</param> /// <returns></returns> public string BuildAuthorizeUrl(RequestToken token) { // Use the existing token, or generate a new one var callForwardUrl = base.BuildAuthorizeUrl(OAuthActionUrl, token); // Store the token in the IEvernoteAuthorizer return callForwardUrl; }
private void btnGetPin_Click(object sender, EventArgs e) { var weiboType = ddlWeibo.Text; var consumer = ConsumerFactory.GetConsumer(weiboType); _requestToken = consumer.GetRequestToken(); var authorizeUri = _requestToken.GetNormalizedAuthorizeUri(); Process.Start(authorizeUri); }
/// <summary> /// Build user authorization URL to authorize request token /// </summary> /// <param name="userAuthorizationUrl">User authorization URL served by Service Provider</param> /// <param name="requestToken">Request token</param> /// <returns>user authorization URL to authorize request token</returns> public static string BuildUserAuthorizationURL( string userAuthorizationUrl, RequestToken requestToken ) { Uri uri = new Uri(userAuthorizationUrl); return uri.OriginalString + (uri.Query != null && uri.Query.Length > 0 ? "&" : "?") + "oauth_token=" + Uri.EscapeDataString(requestToken.TokenValue); }
void gui_response(string from_jid, RequestToken token, string result, string options) { // 此时在窗口线程中执行了 if (token.command() == "test.dc.add_sink" && result == "ok") { SortedDictionary<string, string> kvs = parse_options(options); if (kvs.ContainsKey("sinkid") && kvs.ContainsKey("server_ip") && kvs.ContainsKey("server_rtp_port") && kvs.ContainsKey("server_rtcp_port")) { int sinkid = int.Parse(kvs["sinkid"]); string ip = kvs["server_ip"]; int rtp_port = int.Parse(kvs["server_rtp_port"]); int rtcp_port = int.Parse(kvs["server_rtcp_port"]); // 启动 zk_win_video_render .... zkvr_init(); render_ = zkvr_open(this.Handle, ip, rtp_port, rtcp_port); } } }
public IDisposable Activate () { var requestStack = GetCurrentStack (); RequestToken disposable = new RequestToken (this); disposables.Add (disposable); requestStack.Push (this); return disposable; }
/// <summary> /// This method should be called once you have received the verifier from /// Evernote. It will populate a EvernoteCredentials object with all the /// information you need to authenticate to Evernote as this user /// </summary> /// <remarks> /// This is an asynchronous method /// </remarks> /// <param name="oauth_verifier">The verifier passed in via the QueryString to your endpoint</param> /// <param name="token">The token used to request the authorization - this should be persisted from the call to GetRequestToken</param> /// <returns></returns> public async Task<EvernoteCredentials> ParseAccessToken(string oauth_verifier, RequestToken token) { // If there is no oauth_verifier parameter, then we failed to authorize :( if (oauth_verifier == null) return null; if (token == null) throw new ArgumentNullException("token", "You need to pass in the original token that was generated by BuildAuthorizeUrl"); var result = await base.GetAccessToken(OAuthUrl, token, oauth_verifier, null, null); // There is no extra secret for evernote tokens EvernoteCredentials credentials = new EvernoteCredentials(); credentials.AuthToken = result.Token.Key; // Parse the extra data credentials.Shard = ParseExtraData(result, "edam_shard"); credentials.UserId = ParseExtraData(result, "edam_userId"); var expires = ParseExtraData(result, "edam_expires"); var expiresDateTime = new DateTime(1970, 1, 1).AddTicks(long.Parse(expires) * 10000); credentials.Expires = DateTime.SpecifyKind(expiresDateTime, DateTimeKind.Utc); credentials.NotebookUrl = ParseExtraData(result, "edam_noteStoreUrl"); credentials.WebApiUrlPrefix = ParseExtraData(result, "edam_webApiUrlPrefix"); return credentials; }
/// <summary> /// Returns the URL that the user should be directed to in order to /// upgrade the Request Token to a Access Token. /// </summary> /// <param name="callbackUri">Optional URL that the user will be directed to when finished.</param> /// <param name="token">The Request Token to upgrade.</param> /// <param name="args">Optional additional arguments to include in the request.</param> /// <returns>The redirect URL.</returns> public Uri GetRedirect(Uri callbackUri, RequestToken token, NameValueCollection args) { return OAuthClient.GetAuthenticationRedirect(AuthorizeTokenUrl, callbackUri, token, args); }
/// <summary> /// Using a Request Token, generate the URL that the user must /// visit in order to authorize the token. /// </summary> /// <param name="uri">Destination URL.</param> /// <param name="callbackUri">Optional URL to send the user back to when the token has been verified.</param> /// <param name="token">The Request Token to verify.</param> /// <param name="parameters">Optional additinal parameters to include.</param> /// <returns>A URL to which the user should be directed.</returns> static Uri GetAuthenticationRedirect(Uri uri, Uri callbackUri, RequestToken token, NameValueCollection parameters) { UriBuilder ub = new UriBuilder(uri); NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query); if (token != null) nvc.Add(OAuthArguments.OAuthToken, token.Key); if (callbackUri != null) nvc.Add(OAuthArguments.OAuthCallback, callbackUri.AbsoluteUri); if (parameters != null) nvc.Add(parameters); ub.Query = OAuthUtility.ArgsToVal(nvc, AuthenticationMethod.Get); return ub.Uri; }
/// <summary> /// Request access token responding to authenticated request token. /// </summary> /// <param name="verifier">Verifier string for authenticaed request token</param> /// <param name="requestToken">Authenticated request token</param> /// <param name="accessTokenUrl">Access token URL</param> /// <param name="realm">Realm for requesting access token</param> /// <returns>Responding access token</returns> public AccessToken GetAccessToken(string verifier, RequestToken requestToken, string accessTokenUrl, string realm) { return this.GetAccessToken(verifier, requestToken, accessTokenUrl, realm, CancellationToken.None); }
public GettingWebRequest RequestAccessToken(string verifier, RequestToken requestToken, string accessTokenUrl, string realm) { string oauth_consumer_key = _consumerKey; string oauth_token = requestToken.TokenValue; string oauth_signature_method = "HMAC-SHA1"; string oauth_timestamp = ((DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1).Ticks) / (1000 * 10000)).ToString(); string oauth_nonce = Guid.NewGuid().ToString(); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(accessTokenUrl); #if !SILVERLIGHT req.Timeout = this.Timeout; #endif req.Method = WebRequestMethods.Http.Post; string oauth_signature = CreateHMACSHA1Signature( req.Method, accessTokenUrl, new Parameter[]{ new Parameter("oauth_consumer_key",oauth_consumer_key), new Parameter("oauth_token",oauth_token ), new Parameter ("oauth_signature_method",oauth_signature_method ), new Parameter ("oauth_timestamp",oauth_timestamp), new Parameter ("oauth_nonce",oauth_nonce ), new Parameter ("oauth_verifier",verifier ), }, _consumerSecret, requestToken.TokenSecret ); req.Headers.Add( "Authorization: OAuth " + "realm=\"" + realm + "\"," + "oauth_consumer_key=\"" + Uri.EscapeDataString(oauth_consumer_key) + "\"," + "oauth_token=\"" + Uri.EscapeDataString(oauth_token) + "\"," + "oauth_signature_method=\"" + Uri.EscapeDataString(oauth_signature_method) + "\"," + "oauth_signature=\"" + Uri.EscapeDataString(oauth_signature) + "\"," + "oauth_timestamp=\"" + Uri.EscapeDataString(oauth_timestamp) + "\"," + "oauth_nonce=\"" + Uri.EscapeDataString(oauth_nonce) + "\"," + "oauth_verifier=\"" + Uri.EscapeDataString(verifier) + "\"" ); return new GettingWebRequest(req); }
public async Task <ActionResult <IEnumerable <Sys_Cog_MenuCom> > > r2AddDataModel(MenuCongtyOp options) { try { RequestToken token = CommonData.GetDataFromToken(User); var menuThree = await _context.Sys_Dm_Menu.FindAsync(options.Id); var menuComThree = _context.Sys_Cog_MenuCom.Count(x => x.MenuId == menuThree.Id && x.CompanyId == options.CompanyId); if (menuComThree == 0) { var menuTwo = await _context.Sys_Dm_Menu.FindAsync(menuThree.ParentId); var menuComTwo = _context.Sys_Cog_MenuCom.Count(x => x.MenuId == menuThree.ParentId && x.CompanyId == options.CompanyId); if (menuComTwo == 0) { var menuOne = await _context.Sys_Dm_Menu.FindAsync(menuTwo.ParentId); var menuComOne = _context.Sys_Cog_MenuCom.Count(x => x.MenuId == menuTwo.ParentId && x.CompanyId == options.CompanyId); if (menuComOne == 0) { Sys_Cog_MenuCom objOne = new Sys_Cog_MenuCom(); objOne.MenuId = menuOne.Id; objOne.CompanyId = options.CompanyId; objOne.IsActive = true; objOne.ParentId = null; objOne.UserUpdateId = token.UserID; objOne.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuCom.Add(objOne); Sys_Cog_MenuCom objTwo = new Sys_Cog_MenuCom(); objTwo.MenuId = menuTwo.Id; objTwo.CompanyId = options.CompanyId; objTwo.IsActive = true; objTwo.ParentId = menuOne.Id; objTwo.UserUpdateId = token.UserID; objTwo.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuCom.Add(objTwo); Sys_Cog_MenuCom objThree = new Sys_Cog_MenuCom(); objThree.MenuId = options.Id; objThree.CompanyId = options.CompanyId; objThree.IsActive = true; objThree.ParentId = menuTwo.Id; objThree.UserUpdateId = token.UserID; objThree.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuCom.Add(objThree); } else { Sys_Cog_MenuCom objTwo = new Sys_Cog_MenuCom(); objTwo.MenuId = menuTwo.Id; objTwo.CompanyId = options.CompanyId; objTwo.IsActive = true; objTwo.ParentId = menuOne.Id; objTwo.UserUpdateId = token.UserID; objTwo.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuCom.Add(objTwo); Sys_Cog_MenuCom objThree = new Sys_Cog_MenuCom(); objThree.MenuId = options.Id; objThree.CompanyId = options.CompanyId; objThree.ParentId = menuTwo.Id; objThree.IsActive = true; objThree.UserUpdateId = token.UserID; objThree.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuCom.Add(objThree); } } else { var menuComTwoParent = await _context.Sys_Cog_MenuCom.FirstOrDefaultAsync(x => x.MenuId == menuThree.ParentId && x.CompanyId == options.CompanyId); Sys_Cog_MenuCom objThree = new Sys_Cog_MenuCom(); objThree.MenuId = options.Id; objThree.CompanyId = options.CompanyId; objThree.IsActive = true; objThree.ParentId = menuTwo.Id; objThree.UserUpdateId = token.UserID; objThree.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuCom.Add(objThree); menuComTwoParent.IsActive = true; } } else { var menuCome = await _context.Sys_Cog_MenuCom.FirstOrDefaultAsync(x => x.MenuId == options.Id && x.CompanyId == options.CompanyId); var menuComTwoParent = await _context.Sys_Cog_MenuCom.FirstOrDefaultAsync(x => x.MenuId == menuThree.ParentId && x.CompanyId == options.CompanyId); if (options.IsActive == false) { var rmmenuDeps = _context.Sys_Cog_MenuDep.Where(x => x.MenuId == options.Id && x.CompanyId == options.CompanyId).ToList(); // xóa menu phòng if (_context.Sys_Cog_MenuCom.Count(x => x.ParentId == menuThree.ParentId && x.CompanyId == options.CompanyId && x.IsActive == true && x.MenuId != options.Id) == 0) { menuComTwoParent.IsActive = false; } foreach (var item in rmmenuDeps) { item.IsActive = false; var menuDepParent = await _context.Sys_Cog_MenuDep.FirstOrDefaultAsync(x => x.MenuId == item.ParentId && x.CompanyId == item.CompanyId && x.DepartmentId == item.DepartmentId); if (_context.Sys_Cog_MenuDep.Count(x => x.ParentId == item.ParentId && x.CompanyId == item.CompanyId && x.IsActive == true && x.MenuId != item.MenuId) == 0) { menuDepParent.IsActive = false; } var rmmenuNests = _context.Sys_Cog_MenuNest.Where(x => x.MenuId == options.Id && x.CompanyId == options.CompanyId && x.ParentDepartmentId == item.DepartmentId).ToList(); // xóa menu phòng foreach (var ntem in rmmenuNests) { ntem.IsActive = false; } } menuCome.IsActive = false; menuCome.DateUpdate = DateTime.Now; menuCome.UserUpdateId = token.UserID; } else { if (_context.Sys_Cog_MenuCom.Count(x => x.ParentId == menuThree.ParentId && x.CompanyId == options.CompanyId && x.IsActive == true) == 0) { menuComTwoParent.IsActive = true; } menuCome.IsActive = true; menuCome.DateUpdate = DateTime.Now; menuCome.UserUpdateId = token.UserID; } } await _context.SaveChangesAsync(); return(new ObjectResult(new { error = 0 })); } catch (Exception ez) { return(new ObjectResult(new { error = 1 })); } }
public void SaveRequestToken(RequestToken requestToken) { UserSettings.Default.RequestTokenJson = (requestToken == null) ? string.Empty : JsonConvert.SerializeObject(requestToken, Formatting.None); }
void PersistRequestToken(RequestToken requestToken) { Session["RequestToken"] = requestToken; }
public async Task <ActionResult <IEnumerable <Sys_Cog_MenuNest> > > r2AddDataModelNest(MenuCongtyNest options) { try { RequestToken token = CommonData.GetDataFromToken(User); var menuThree = await _context.Sys_Dm_Menu.FindAsync(options.Id); var menuComThree = _context.Sys_Cog_MenuNest.Count(x => x.MenuId == menuThree.Id && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); if (menuComThree == 0) { var menuTwo = await _context.Sys_Dm_Menu.FindAsync(menuThree.ParentId); var menuComTwo = _context.Sys_Cog_MenuNest.Count(x => x.MenuId == menuThree.ParentId && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); if (menuComTwo == 0) { var menuOne = await _context.Sys_Dm_Menu.FindAsync(menuTwo.ParentId); var menuComOne = _context.Sys_Cog_MenuNest.Count(x => x.MenuId == menuTwo.ParentId && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); if (menuComOne == 0) { Sys_Cog_MenuNest objOne = new Sys_Cog_MenuNest(); objOne.MenuId = menuOne.Id; objOne.CompanyId = options.CompanyId; objOne.IsActive = true; objOne.ParentId = null; objOne.DepartmentId = options.NestId; objOne.ParentDepartmentId = options.DepartmentId; objOne.UserUpdateId = token.UserID; objOne.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuNest.Add(objOne); Sys_Cog_MenuNest objTwo = new Sys_Cog_MenuNest(); objTwo.MenuId = menuTwo.Id; objTwo.CompanyId = options.CompanyId; objTwo.IsActive = true; objTwo.ParentId = menuOne.Id; objTwo.DepartmentId = options.NestId; objTwo.ParentDepartmentId = options.DepartmentId; objTwo.UserUpdateId = token.UserID; objTwo.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuNest.Add(objTwo); Sys_Cog_MenuNest objThree = new Sys_Cog_MenuNest(); objThree.MenuId = options.Id; objThree.CompanyId = options.CompanyId; objThree.IsActive = true; objThree.ParentId = menuTwo.Id; objThree.DepartmentId = options.NestId; objThree.ParentDepartmentId = options.DepartmentId; objThree.UserUpdateId = token.UserID; objThree.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuNest.Add(objThree); } else { Sys_Cog_MenuNest objTwo = new Sys_Cog_MenuNest(); objTwo.MenuId = menuTwo.Id; objTwo.CompanyId = options.CompanyId; objTwo.IsActive = true; objTwo.ParentId = menuOne.Id; objTwo.DepartmentId = options.NestId; objTwo.ParentDepartmentId = options.DepartmentId; objTwo.UserUpdateId = token.UserID; objTwo.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuNest.Add(objTwo); Sys_Cog_MenuNest objThree = new Sys_Cog_MenuNest(); objThree.MenuId = options.Id; objThree.CompanyId = options.CompanyId; objThree.ParentId = menuTwo.Id; objThree.IsActive = true; objThree.DepartmentId = options.NestId; objThree.ParentDepartmentId = options.DepartmentId; objThree.UserUpdateId = token.UserID; objThree.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuNest.Add(objThree); } } else { Sys_Cog_MenuNest objThree = new Sys_Cog_MenuNest(); objThree.MenuId = options.Id; objThree.CompanyId = options.CompanyId; objThree.IsActive = true; objThree.ParentId = menuTwo.Id; objThree.DepartmentId = options.NestId; objThree.ParentDepartmentId = options.DepartmentId; objThree.UserUpdateId = token.UserID; objThree.DateUpdate = DateTime.Now; _context.Sys_Cog_MenuNest.Add(objThree); if (_context.Sys_Cog_MenuNest.Count(x => x.IsActive == true && x.ParentId == menuThree.ParentId && x.CompanyId == options.CompanyId && x.MenuId != options.Id && x.DepartmentId == options.NestId) == 0) { var menuTwoParent = await _context.Sys_Cog_MenuNest.FirstOrDefaultAsync(x => x.MenuId == menuThree.ParentId && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); menuTwoParent.IsActive = true; if (_context.Sys_Cog_MenuNest.Count(x => x.IsActive == true && x.ParentId == menuTwoParent.ParentId && x.CompanyId == options.CompanyId && x.MenuId != menuTwoParent.MenuId && x.DepartmentId == options.NestId) == 0) { var menuoneParent = await _context.Sys_Cog_MenuNest.FirstOrDefaultAsync(x => x.MenuId == menuTwoParent.ParentId && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); menuoneParent.IsActive = true; } } } } else { var menuCome = await _context.Sys_Cog_MenuNest.FirstOrDefaultAsync(x => x.MenuId == options.Id && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); if (options.IsActive == false) { if (_context.Sys_Cog_MenuNest.Count(x => x.IsActive == true && x.ParentId == menuCome.ParentId && x.CompanyId == options.CompanyId && x.MenuId != options.Id && x.DepartmentId == options.NestId) == 0) { var menuTwoParent = await _context.Sys_Cog_MenuNest.FirstOrDefaultAsync(x => x.MenuId == menuCome.ParentId && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); menuTwoParent.IsActive = false; if (_context.Sys_Cog_MenuNest.Count(x => x.IsActive == true && x.ParentId == menuTwoParent.ParentId && x.CompanyId == options.CompanyId && x.MenuId != menuTwoParent.MenuId && x.DepartmentId == options.NestId) == 0) { var menuoneParent = await _context.Sys_Cog_MenuNest.FirstOrDefaultAsync(x => x.MenuId == menuTwoParent.ParentId && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); menuoneParent.IsActive = false; } } menuCome.IsActive = false; menuCome.UserUpdateId = token.UserID; menuCome.DateUpdate = DateTime.Now; } else { if (_context.Sys_Cog_MenuNest.Count(x => x.IsActive == true && x.ParentId == menuCome.ParentId && x.CompanyId == options.CompanyId && x.MenuId != options.Id && x.DepartmentId == options.NestId) == 0) { var menuTwoParent = await _context.Sys_Cog_MenuNest.FirstOrDefaultAsync(x => x.MenuId == menuCome.ParentId && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); menuTwoParent.IsActive = true; if (_context.Sys_Cog_MenuNest.Count(x => x.IsActive == true && x.ParentId == menuTwoParent.ParentId && x.CompanyId == options.CompanyId && x.MenuId != menuTwoParent.MenuId && x.DepartmentId == options.NestId) == 0) { var menuoneParent = await _context.Sys_Cog_MenuNest.FirstOrDefaultAsync(x => x.MenuId == menuTwoParent.ParentId && x.CompanyId == options.CompanyId && x.DepartmentId == options.NestId); menuoneParent.IsActive = true; } } menuCome.IsActive = true; menuCome.UserUpdateId = token.UserID; menuCome.DateUpdate = DateTime.Now; } } await _context.SaveChangesAsync(); return(new ObjectResult(new { error = 0 })); } catch (Exception) { return(new ObjectResult(new { error = 1 })); } }
public async Task <ActionResult <IEnumerable <Sys_Dm_User> > > CheckLogin([FromBody] CheckLogin checklogin) { try { string PasswordEn = Helper.Encrypt(checklogin.UserName, checklogin.Password); //var useronline = _onlinecontext.Sys_Dm_Lisesion.Count(x => x.Login == true && x.HanDung >= DateTime.Now); // online check //var checkadmin = _onlinecontext.Sys_Dm_Lisesion.Count(x => x.UserName == checklogin.UserName && x.Password == PasswordEn); // online check var user = _context.Sys_Dm_User.FirstOrDefault(x => x.Username == checklogin.UserName && x.Password == PasswordEn); if (user == null) { return(new JsonResult(new { error = 1, ms = "Tài khoản hoặc mật khẩu không chính xác. Vui lòng kiểm tra lại!" })); } RequestToken token = new RequestToken() { UserID = user.Id, CompanyId = user.CompanyId ?? 0 }; string tk = GenerateTokenData(token);; var congTys = await _context.Sys_Dm_Company.Where(x => x.IsActive == true).Select(a => new { Name = "(" + a.Code + ") " + a.Name, a.Id }).ToListAsync(); switch (user.Role) { #region Nhóm quản trị tổng perMission = 0 case RoleUserEnum.Administrator: var companyId = congTys[0].Id; var _listMenuAdmin = await(from b in _context.Sys_Dm_Menu.Where(x => x.IsActive == true) select new { b.Id, b.IsOrder, name = b.Name, url = b.RouterLink, icon = b.IconMenu, title = b.IsTitle, b.MenuRank, b.ParentId, }).ToListAsync(); return(new JsonResult(new { token = tk, u = new { user.Id, user.FullName, user.CompanyId, user.DepartmentId, Permission = 0, GroupRoleDeFault = user.Role, CompanyIdDefault = companyId, } , _listNhomQuyen = await(from a in _context.Sys_Cog_UsersGroup join b in _context.Sys_Dm_GroupRole on a.GroupRoleId equals b.Id where a.UserId == user.Id orderby b.RankRole select new { a.GroupRoleId, b.Name }).ToListAsync() , _listQuyen = await(from b in _context.Sys_Dm_Menu.Where(x => x.IsActive == true) select new { b.Id, b.RouterLink, ViewPer = true, AddPer = true, EditPer = true, DelPer = true, ExportPer = true, }).ToListAsync(), data = _listMenuAdmin.Where(x => x.MenuRank < 3).Select(a => new { a.Id, a.IsOrder, a.name, a.url, a.icon, a.MenuRank, a.title, children = _listMenuAdmin.Where(x => x.MenuRank >= 3 && x.ParentId == a.Id).Select(b => new { b.Id, b.name, b.url, b.icon, b.title, b.IsOrder }).OrderBy(y => y.IsOrder) }).OrderBy(y => y.IsOrder), congTys, error = 0 })); #endregion #region Nhóm quản trị công ty case RoleUserEnum.AdminCompany: var _listMenuCustomers = await(from a in _context.Sys_Cog_MenuCom join b in _context.Sys_Dm_Menu on a.MenuId equals b.Id where a.CompanyId == user.CompanyId && b.IsActive == true && a.IsActive == true select new { name = b.Name, url = b.RouterLink, icon = b.IconMenu, title = b.IsTitle, b.ParentId, b.MenuRank, b.Id, b.IsOrder, ViewPer = true, AddPer = true, EditPer = true, DelPer = true, ExportPer = true, b.RouterLink }).ToListAsync(); var _listMenuExitst = await(from a in _context.Sys_Cog_MenuCom where a.CompanyId == user.CompanyId && a.IsActive == true group a by a.ParentId into c select new { ParentId = c.Key }).ToListAsync(); return(new JsonResult(new { token = tk, u = new { user.Id, user.FullName, user.CompanyId, user.DepartmentId, Permission = 1, GroupRoleDeFault = user.Role, CompanyIdDefault = user.CompanyId, } , _listNhomQuyen = await(from a in _context.Sys_Cog_UsersGroup join b in _context.Sys_Dm_GroupRole on a.GroupRoleId equals b.Id where a.UserId == user.Id orderby b.RankRole select new { a.GroupRoleId, b.Name }).ToListAsync() , _listQuyen = _listMenuCustomers.Select(a => new { a.Id, a.AddPer, a.ViewPer, a.EditPer, a.DelPer, a.ExportPer, a.RouterLink }), data = _listMenuCustomers.Where(x => x.MenuRank < 3 && _listMenuExitst.Count(e => e.ParentId == x.Id) > 0).Select(a => new { a.Id, a.name, a.url, a.icon, a.MenuRank, a.title, a.IsOrder, children = _listMenuCustomers.Where(x => x.MenuRank >= 3 && x.ParentId == a.Id).Select(b => new { b.Id, b.name, b.url, b.icon, b.title, b.IsOrder }).OrderBy(y => y.IsOrder) }).OrderBy(y => y.IsOrder), congTys = new List <Sys_Dm_Company>(), error = 0 })); #endregion #region Nhóm quản trị chi nhánh case RoleUserEnum.AdminBranch: var _listMenuCustomerBranchs = await(from a in _context.Sys_Cog_MenuCom join b in _context.Sys_Dm_Menu on a.MenuId equals b.Id where a.CompanyId == user.CompanyId && b.IsActive == true && a.IsActive == true select new { name = b.Name, url = b.RouterLink, icon = b.IconMenu, title = b.IsTitle, b.ParentId, b.MenuRank, b.Id, b.IsOrder, ViewPer = true, AddPer = true, EditPer = true, DelPer = true, ExportPer = true, b.RouterLink }).ToListAsync(); var _listMenuBranchExitst = await(from a in _context.Sys_Cog_MenuCom where a.CompanyId == user.CompanyId && a.IsActive == true group a by a.ParentId into c select new { ParentId = c.Key }).ToListAsync(); return(new JsonResult(new { token = tk, u = new { user.Id, user.FullName, user.CompanyId, user.DepartmentId, Permission = 1, GroupRoleDeFault = user.Role, CompanyIdDefault = user.CompanyId, } , _listNhomQuyen = await(from a in _context.Sys_Cog_UsersGroup join b in _context.Sys_Dm_GroupRole on a.GroupRoleId equals b.Id where a.UserId == user.Id orderby b.RankRole select new { a.GroupRoleId, b.Name }).ToListAsync() , _listQuyen = _listMenuCustomerBranchs.Select(a => new { a.Id, a.AddPer, a.ViewPer, a.EditPer, a.DelPer, a.ExportPer, a.RouterLink }), data = _listMenuCustomerBranchs.Where(x => x.MenuRank < 3 && _listMenuBranchExitst.Count(e => e.ParentId == x.Id) > 0).Select(a => new { a.Id, a.name, a.url, a.icon, a.MenuRank, a.title, a.IsOrder, children = _listMenuCustomerBranchs.Where(x => x.MenuRank >= 3 && x.ParentId == a.Id).Select(b => new { b.Id, b.name, b.url, b.icon, b.title, b.IsOrder }).OrderBy(y => y.IsOrder) }).OrderBy(y => y.IsOrder), congTys = new List <Sys_Dm_Company>(), error = 0 })); #endregion #region Nhóm quản trị phòng case RoleUserEnum.AdminDepartment: var _listMenuDepartments = await(from a in _context.Sys_Cog_MenuDep join b in _context.Sys_Dm_Menu on a.MenuId equals b.Id where a.DepartmentId == user.DepartmentId && b.IsActive == true && a.IsActive == true && a.CompanyId == user.CompanyId select new { name = b.Name, url = b.RouterLink, icon = b.IconMenu, title = b.IsTitle, b.ParentId, b.MenuRank, b.Id, b.IsOrder, ViewPer = true, AddPer = true, EditPer = true, DelPer = true, ExportPer = true, b.RouterLink }).ToListAsync(); return(new JsonResult(new { token = tk, u = new { user.Id, user.FullName, user.DepartmentId, user.CompanyId, Permission = 2, GroupRoleDeFault = user.Role, CompanyIdDefault = user.CompanyId } , _listNhomQuyen = await(from a in _context.Sys_Cog_UsersGroup join b in _context.Sys_Dm_GroupRole on a.GroupRoleId equals b.Id where a.UserId == user.Id orderby b.RankRole select new { a.GroupRoleId, b.Name }).ToListAsync() , _listQuyen = _listMenuDepartments.Select(a => new { a.Id, a.AddPer, a.ViewPer, a.EditPer, a.DelPer, a.ExportPer, a.RouterLink }), data = _listMenuDepartments.Where(x => x.MenuRank < 3).Select(a => new { a.Id, a.IsOrder, a.name, a.url, a.icon, a.MenuRank, a.title, children = _listMenuDepartments.Where(x => x.MenuRank >= 3 && x.ParentId == a.Id).Select(b => new { b.Id, b.name, b.url, b.icon, b.title, b.IsOrder }).OrderBy(y => y.IsOrder) }).OrderBy(y => y.IsOrder), congTys = new List <Sys_Dm_Company>(), departments = new List <Sys_Dm_Department>(), error = 0 })); #endregion #region Nhóm quản trị tổ case RoleUserEnum.AdminNest: var _listMenuNest = await(from a in _context.Sys_Cog_MenuNest join b in _context.Sys_Dm_Menu on a.MenuId equals b.Id where a.DepartmentId == user.DepartmentId && b.IsActive == true && a.IsActive == true select new { name = b.Name, url = b.RouterLink, icon = b.IconMenu, title = b.IsTitle, b.ParentId, b.MenuRank, b.Id, b.IsOrder, ViewPer = true, AddPer = true, EditPer = true, DelPer = true, ExportPer = true, b.RouterLink }).ToListAsync(); return(new JsonResult(new { token = tk, u = new { user.Id, user.FullName, user.DepartmentId, user.CompanyId, Permission = 3, GroupRoleDeFault = user.Role, CompanyIdDefault = user.CompanyId } , _listNhomQuyen = await(from a in _context.Sys_Cog_UsersGroup join b in _context.Sys_Dm_GroupRole on a.GroupRoleId equals b.Id where a.UserId == user.Id orderby b.RankRole select new { a.GroupRoleId, b.Name }).ToListAsync() , _listQuyen = _listMenuNest.Select(a => new { a.Id, a.AddPer, a.ViewPer, a.EditPer, a.DelPer, a.ExportPer, a.RouterLink }), data = _listMenuNest.Where(x => x.MenuRank < 3).Select(a => new { a.Id, a.IsOrder, a.name, a.url, a.icon, a.MenuRank, a.title, children = _listMenuNest.Where(x => x.MenuRank >= 3 && x.ParentId == a.Id).Select(b => new { b.Id, b.name, b.url, b.icon, b.title, b.IsOrder }).OrderBy(y => y.IsOrder) }).OrderBy(y => y.IsOrder), congTys = new List <Sys_Dm_Company>(), departments = new List <Sys_Dm_Department>(), error = 0 })); #endregion #region Nhóm thường default: var _listMenuNNormal = await(from a in _context.Sys_Cog_Permission join b in _context.Sys_Dm_Menu on a.MenuId equals b.Id where a.DepartmentId == user.DepartmentId && b.IsActive == true where a.CompanyId == user.CompanyId && a.DepartmentId == user.DepartmentId && a.ViewPer == true select new { name = b.Name, url = b.RouterLink, icon = b.IconMenu, title = b.IsTitle, b.ParentId, b.MenuRank, b.Id, b.IsOrder, ViewPer = true, AddPer = true, EditPer = true, DelPer = true, ExportPer = true, b.RouterLink }).ToListAsync(); return(new JsonResult(new { token = tk, u = new { user.Id, user.FullName, user.DepartmentId, user.CompanyId, Permission = 4, GroupRoleDeFault = user.Role, CompanyIdDefault = user.CompanyId } , _listQuyen = _listMenuNNormal.Select(a => new { a.Id, a.AddPer, a.ViewPer, a.EditPer, a.DelPer, a.ExportPer, a.RouterLink }), data = _listMenuNNormal.Where(x => x.MenuRank < 3).Select(a => new { a.Id, a.IsOrder, a.name, a.url, a.icon, a.MenuRank, a.title, children = _listMenuNNormal.Where(x => x.MenuRank >= 3 && x.ParentId == a.Id).Select(b => new { b.Id, b.name, b.url, b.icon, b.title, b.IsOrder }).OrderBy(y => y.IsOrder) }).OrderBy(y => y.IsOrder), congTys = new List <Sys_Dm_Company>(), departments = new List <Sys_Dm_Department>(), error = 0 })); #endregion } } catch (Exception ex) { return(new ObjectResult(new { error = 1, ms = ex.Message })); } }
/// <summary> /// This method should be called once you have received the verifier from /// Evernote. It will populate a EvernoteCredentials object with all the /// information you need to authenticate to Evernote as this user /// </summary> /// <remarks> /// This is an asynchronous method /// </remarks> /// <param name="oauth_verifier">The verifier passed in via the QueryString to your endpoint</param> /// <param name="token">The token used to request the authorization - this should be persisted from the call to GetRequestToken</param> /// <returns></returns> public async Task <EvernoteCredentials> ParseAccessToken(string oauth_verifier, RequestToken token) { // If there is no oauth_verifier parameter, then we failed to authorize :( if (oauth_verifier == null) { return(null); } if (token == null) { throw new ArgumentNullException("token", "You need to pass in the original token that was generated by BuildAuthorizeUrl"); } var result = await base.GetAccessToken(OAuthUrl, token, oauth_verifier, null, null); // There is no extra secret for evernote tokens EvernoteCredentials credentials = new EvernoteCredentials(); credentials.AuthToken = result.Token.Key; // Parse the extra data credentials.Shard = ParseExtraData(result, "edam_shard"); credentials.UserId = ParseExtraData(result, "edam_userId"); var expires = ParseExtraData(result, "edam_expires"); var expiresDateTime = new DateTime(1970, 1, 1).AddTicks(long.Parse(expires) * 10000); credentials.Expires = DateTime.SpecifyKind(expiresDateTime, DateTimeKind.Utc); credentials.NotebookUrl = ParseExtraData(result, "edam_noteStoreUrl"); credentials.WebApiUrlPrefix = ParseExtraData(result, "edam_webApiUrlPrefix"); return(credentials); }
public string GenerateAuthUrlFromRequestToken(RequestToken token, bool forceLogoutBeforeAuth) { var url = Constants.BaseApiUrl + (forceLogoutBeforeAuth ? Constants.LogoutAndAuthorizeUri : Constants.AuthorizeUri); return(string.Format("{0}?oauth_token={1}", url, token.Token)); }
public async Task <ActionResult <IEnumerable <VB_QT_Buoc> > > r1GetListDataLenhTheoUser(LenhMenuForUserOfMyWork options) { try { RequestToken token = CommonData.GetDataFromToken(User); var user = await _context.Sys_Dm_User.FindAsync(token.UserID); var workFlows = _context.CV_QT_WorkFlow.Where(x => x.MyWorkId == options.MyWorkId).Select(x => x.TypeFlow).Distinct().ToList(); var myWork = await _context.CV_QT_MyWork.FindAsync(options.MyWorkId); List <string> list = new List <string>(); if (myWork != null) { if (myWork.CycleWork == 0) { list.Add("CV_TRINHHOANTHANH"); } } if (!workFlows.Contains(1) && !workFlows.Contains(13)) { list.Add("CV_TRINHHOANTHANH"); list.Add("CV_TRINHCHINHSUA"); } if (workFlows.Contains(1)) { list.Add("CV_TRINHTHOIHAN"); list.Add("CV_TRINHCHINHSUA"); } if (workFlows.Contains(2) || workFlows.Contains(3)) { list.Add("CV_TRINHTHOIHAN"); list.Add("CV_DUYETTHOIHAN"); } if (workFlows.Contains(4) && !workFlows.Contains(5)) { list.Add("CV_TRINHHOANTHANH"); } if (workFlows.Contains(6)) { list.Add("CV_TRINHHOANTHANH"); list.Add("CV_DUYETHOANTHANH"); } if (workFlows.Contains(13)) { list.Add("CV_TRINHTHOIHAN"); list.Add("CV_TRINHCHINHSUA"); } if (workFlows.Contains(14) && workFlows.Contains(16)) { list.Add("CV_KHOITAOSAU"); list.Add("CV_DUYETKHOITAOSAU"); } var tables = from a in _context.VB_QT_BuocLenhGroupRole where a != null join b in _context.VB_QT_BuocLenhTuongTac on a.BuocLenhTuongTacId equals b.Id join c in _context.VB_QT_LenhTuongTac on b.LenhTuongTacId equals c.Id join d in _context.VB_QT_Buoc on b.BuocId equals d.Id where a.GroupRoleId == options.GroupRoleId && d.MenuId == options.MenuId && !list.Contains(c.Code) select new { c.Name, BuocLenhGroupId = a.Id, c.IsActive, c.IsOrder, c.Code }; var qrs = await tables.OrderBy(x => x.IsOrder).ToListAsync(); return(new ObjectResult(new { error = 0, data = qrs })); } catch (Exception) { return(new ObjectResult(new { error = 1 })); } }
public AuthCredential ProcessApprovedAuthCallback(RequestToken token) { if (string.IsNullOrWhiteSpace(token.Token)) { throw new Exception("RequestToken.Token must not be null"); } //else if client.Authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret); var request = new RestRequest("oauth/access_token", Method.POST); client.Authenticator = OAuth1Authenticator.ForAccessToken( this.ConsumerKey, this.ConsumerSecret, token.Token, token.Secret, token.Verifier ); var response = client.Execute(request); //Assert.NotNull(response); //Assert.Equal(HttpStatusCode.OK, response.StatusCode); if (response.StatusCode != HttpStatusCode.OK) { throw new FitbitException(response.Content, response.StatusCode); } var qs = HttpUtility.ParseQueryString(response.Content); //not actually parsing querystring, but body is formatted like htat var oauth_token = qs["oauth_token"]; var oauth_token_secret = qs["oauth_token_secret"]; var encoded_user_id = qs["encoded_user_id"]; //Assert.NotNull(oauth_token); //Assert.NotNull(oauth_token_secret); /* * request = new RestRequest("account/verify_credentials.xml"); * client.Authenticator = OAuth1Authenticator.ForProtectedResource( * this.ConsumerKey, this.ConsumerSecret, oauth_token, oauth_token_secret * ); * * response = client.Execute(request); * */ return(new AuthCredential() { AuthToken = oauth_token, AuthTokenSecret = oauth_token_secret, UserId = encoded_user_id }); //Assert.NotNull(response); //Assert.Equal(HttpStatusCode.OK, response.StatusCode); //request = new RestRequest("statuses/update.json", Method.POST); //request.AddParameter("status", "Hello world! " + DateTime.Now.Ticks.ToString()); //client.Authenticator = OAuth1Authenticator.ForProtectedResource( // consumerKey, consumerSecret, oauth_token, oauth_token_secret //); //response = client.Execute(request); //Assert.NotNull(response); //Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { IReadableStringCollection query = Request.Query; string protectedRequestToken = Request.Cookies[StateCookie]; RequestToken requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken); if (requestToken == null) { _logger.WriteWarning("Invalid state"); return(null); } properties = requestToken.Properties; string returnedToken = query.Get("oauth_token"); if (string.IsNullOrWhiteSpace(returnedToken)) { _logger.WriteWarning("Missing oauth_token"); return(new AuthenticationTicket(null, properties)); } if (returnedToken != requestToken.Token) { _logger.WriteWarning("Unmatched token"); return(new AuthenticationTicket(null, properties)); } string oauthVerifier = query.Get("oauth_verifier"); if (string.IsNullOrWhiteSpace(oauthVerifier)) { _logger.WriteWarning("Missing or blank oauth_verifier"); return(new AuthenticationTicket(null, properties)); } AccessToken accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken, oauthVerifier); JObject userCard = await ObtainUserProfile(Options.ConsumerKey, Options.ConsumerSecret, accessToken, oauthVerifier); var context = new YahooAuthenticatedContext(Context, userCard, accessToken.UserId, accessToken.Token, accessToken.TokenSecret); context.Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); if (!String.IsNullOrEmpty(context.UserId)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } if (!String.IsNullOrEmpty(context.NickName)) { context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.NickName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } if (!String.IsNullOrEmpty(context.Email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } if (!String.IsNullOrEmpty(context.UserId)) { context.Identity.AddClaim(new Claim("urn:yahoo:userid", context.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } if (!String.IsNullOrEmpty(context.NickName)) { context.Identity.AddClaim(new Claim("urn:yahoo:nickname", context.NickName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } context.Properties = requestToken.Properties; Response.Cookies.Delete(StateCookie); await Options.Provider.Authenticated(context); return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception ex) { _logger.WriteError("Authentication failed", ex); return(new AuthenticationTicket(null, properties)); } }
private async Task <AccessToken> ObtainAccessTokenAsync(string appKey, string appSecret, RequestToken token, string verifier) { string normalizedUrl; string normalizedRequestParameters; var oauthBase = new OAuthBase(); var url = new Uri(BaseUri + AccessTokenEndpoint); var signature = oauthBase.GenerateSignature( url, appKey, appSecret, token.Token, verifier, "POST", oauthBase.GenerateTimeStamp(), oauthBase.GenerateNonce(), "", out normalizedUrl, out normalizedRequestParameters); var postData = normalizedRequestParameters + "&oauth_signature=" + HttpUtility.UrlEncode(signature); var authorizationParts = new SortedDictionary <string, string>(); foreach (var key in postData.Split('&')) { authorizationParts.Add(key.Split('=')[0], key.Split('=')[1]); } var authorizationHeaderBuilder = new StringBuilder(); authorizationHeaderBuilder.Append("OAuth "); foreach (var authorizationPart in authorizationParts) { authorizationHeaderBuilder.AppendFormat( "{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value)); } authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2; string query = await WebRequestAsync(HttpMethod.Post, normalizedUrl, authorizationHeaderBuilder.ToString()); if (query.Length > 0) { var responseParameters = HttpUtility.ParseQueryString(query); if (responseParameters["oauth_token"] != null) { return(new AccessToken { Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), Shard = Uri.UnescapeDataString(responseParameters["edam_shard"]), UserId = Uri.UnescapeDataString(responseParameters["edam_userId"]), NoteStoreUrl = Uri.UnescapeDataString(responseParameters["edam_noteStoreUrl"]), WebApiUrlPrefix = Uri.UnescapeDataString(responseParameters["edam_webApiUrlPrefix"]), }); } } return(new AccessToken()); }
private async Task <AccessToken> ObtainAccessTokenAsync(string appKey, string appSecret, RequestToken token, string verifier) { _logger.WriteVerbose("ObtainAccessToken"); var nonce = Guid.NewGuid().ToString("N"); var authorizationParts = new SortedDictionary <string, string> { { "oauth_consumer_key", appKey }, { "oauth_nonce", nonce }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_token", token.Token }, { "oauth_timestamp", GenerateTimeStamp() }, { "oauth_verifier", verifier }, { "oauth_version", "1.0" }, }; var parameterBuilder = new StringBuilder(); foreach (var authorizationKey in authorizationParts) { parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(authorizationKey.Key), Uri.EscapeDataString(authorizationKey.Value)); } parameterBuilder.Length--; var parameterString = parameterBuilder.ToString(); var canonicalRequestBuilder = new StringBuilder(); canonicalRequestBuilder.Append(HttpMethod.Post.Method); canonicalRequestBuilder.Append("&"); canonicalRequestBuilder.Append(Uri.EscapeDataString(AccessTokenEndpoint)); canonicalRequestBuilder.Append("&"); canonicalRequestBuilder.Append(Uri.EscapeDataString(parameterString)); var signature = ComputeSignature(appSecret, token.TokenSecret, canonicalRequestBuilder.ToString()); authorizationParts.Add("oauth_signature", signature); var authorizationHeaderBuilder = new StringBuilder(); authorizationHeaderBuilder.Append("OAuth "); foreach (var authorizationPart in authorizationParts) { authorizationHeaderBuilder.AppendFormat( "{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value)); } authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2; var request = new HttpRequestMessage(HttpMethod.Post, AccessTokenEndpoint); request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString()); var formPairs = new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("oauth_verifier", verifier) }; request.Content = new FormUrlEncodedContent(formPairs); var response = await _httpClient.SendAsync(request, Request.CallCancelled); if (!response.IsSuccessStatusCode) { _logger.WriteError("AccessToken request failed with a status code of " + response.StatusCode); response.EnsureSuccessStatusCode(); // throw } var responseText = await response.Content.ReadAsStringAsync(); var responseParameters = WebHelpers.ParseForm(responseText); return(new AccessToken { Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), UserId = Uri.UnescapeDataString(responseParameters["user_nsid"]), UserName = Uri.UnescapeDataString(responseParameters["username"]), FullName = Uri.UnescapeDataString(responseParameters["fullname"]), }); }
public async Task <ActionResult <IEnumerable <VB_QT_Buoc> > > r1GetListDataMohinhToChuc(BuocLenhGroupForUser options) { try { RequestToken token = CommonData.GetDataFromToken(User); var user = await _context.Sys_Dm_User.FindAsync(token.UserID); int hienNguoiNhan = CheckNguoiNhan.DuocHienThiNguoiNhan(_context, options.GroupRoleId, options.BuocLenhGroupId); switch (hienNguoiNhan) { #region Toàn công ty case 0: var _listUniOn = await _context.Sys_Dm_Department.Where(x => x.ParentId == null && x.CompanyId == 1).Select(a => new { a.Id, a.Name, ParentId = a.CompanyId, Loai = 1 }).Union( _context.Sys_Dm_Company.Where(x => x.ParentId == 1).Select(c => new { c.Id, c.Name, ParentId = 1, Loai = 0 })).ToListAsync(); var _listDepartMenttct = _context.Sys_Dm_Department.Where(x => x.ParentId == null).Select(a => new { a.Id, a.Name, a.CompanyId, Loai = 1, children = _context.Sys_Dm_Department.Where(x => x.ParentId == a.Id).Select(v => new { v.Id, v.Name, Loai = 2 }).ToList() }); var s = _listUniOn.Select(x => new { x.Id, x.Name, x.ParentId, x.Loai, children = x.Loai == 0 ? _listDepartMenttct.Where(b => b.CompanyId == x.Id).Select(k => new { k.Id, k.Name, k.Loai, k.children }).ToList() : _listDepartMenttct.Where(b => b.CompanyId == 0).Select(k => new { k.Id, k.Name, k.Loai, k.children }).ToList() }); var tables = (from a in _context.Sys_Dm_Company where a.ParentId == null select new { a.Id, a.Name, Loai = 0, a.IsOrder, children = s.ToList() }).ToList(); return(new ObjectResult(new { error = 0, data = tables.OrderBy(x => x.IsOrder) })); #endregion #region Công ty mẹ case 1: var _listDepartMentctm = _context.Sys_Dm_Department.Where(x => x.ParentId == null).Select(a => new { a.Id, a.Name, a.CompanyId, Loai = 1, children = _context.Sys_Dm_Department.Where(x => x.ParentId == a.Id).Select(v => new { v.Id, v.Name, Loai = 2 }).ToList() }); var tables2 = (from a in _context.Sys_Dm_Company where a.ParentId == null select new { a.Id, a.Name, Loai = 0, children = _listDepartMentctm.Where(x => x.CompanyId == a.Id).Select(c => new { c.Id, c.Name, c.Loai, c.children }).ToList() }).ToList(); return(new ObjectResult(new { error = 0, data = tables2 })); #endregion #region Công ty hiện tại case 2: var _listDepartMentctc = _context.Sys_Dm_Department.Where(x => x.ParentId == null).Select(a => new { a.Id, a.Name, a.CompanyId, Loai = 1, children = _context.Sys_Dm_Department.Where(x => x.ParentId == a.Id).Select(v => new { v.Id, v.Name, Loai = 2 }).ToList() }); var tables3 = (from a in _context.Sys_Dm_Company where a.Id == user.CompanyId select new { a.Id, a.Name, Loai = 0, children = _listDepartMentctc.Where(x => x.CompanyId == user.CompanyId).Select(c => new { c.Id, c.Name, c.Loai, c.children }).ToList() }).ToList(); return(new ObjectResult(new { error = 0, data = tables3 })); #endregion #region Phòng ban case 3: int DepId = 0; var room = await _context.Sys_Dm_Department.FindAsync(user.DepartmentId); if (room.ParentId == null) { DepId = room.Id; } else { DepId = room.ParentId ?? 0; } var _listDepartMents = _context.Sys_Dm_Department.Where(x => x.CompanyId == user.CompanyId && x.Id == DepId).Select(a => new { a.Id, a.Name, a.CompanyId, Loai = 1, children = _context.Sys_Dm_Department.Where(x => x.ParentId == a.Id).Select(v => new { v.Id, v.Name, Loai = 2 }).ToList() }); return(new ObjectResult(new { error = 0, data = _listDepartMents })); #endregion #region Tổ case 4: var _listDepartMentTo = (_context.Sys_Dm_Department.Where(x => x.CompanyId == user.CompanyId && x.Id == user.DepartmentId).Select(a => new { a.Id, a.Name, a.CompanyId, Loai = 2, children = _context.Sys_Dm_Department.Where(x => x.ParentId == a.Id).Select(v => new { v.Id, v.Name, Loai = 2 }).ToList() })).ToList(); return(new ObjectResult(new { error = 0, data = _listDepartMentTo })); #endregion default: var _listDepartMentToe = (_context.Sys_Dm_Department.Where(x => x.CompanyId == user.CompanyId && x.Id == user.DepartmentId).Select(a => new { a.Id, a.Name, a.CompanyId, Loai = 2, children = _context.Sys_Dm_Department.Where(x => x.ParentId == a.Id).Select(v => new { v.Id, v.Name, Loai = 2 }).ToList() })).ToList(); return(new ObjectResult(new { error = 0, data = _listDepartMentToe })); } } catch (Exception ex) { return(new ObjectResult(new { error = 1 })); } }
public AccessToken GetAccessToken(string verifier, RequestToken requestToken, string accessTokenUrl, string realm, CancellationToken token) { return AccessToken.FromRequest(RequestAccessToken(verifier, requestToken, accessTokenUrl, realm), token); }
public async Task <ActionResult <IEnumerable <VB_QT_Buoc> > > r1GetListUserNhanViec(BuocLenhGroupForUser options) { try { RequestToken token = CommonData.GetDataFromToken(User); var user = await _context.Sys_Dm_User.FindAsync(token.UserID); var buoc = _context.VB_QT_Buoc.FirstOrDefault(x => x.MenuId == options.MenuId); var LenhTuongTac = _context.VB_QT_LenhTuongTac.FirstOrDefault(x => x.Code == options.MaLenh); var buocLenhTuongTac = _context.VB_QT_BuocLenhTuongTac.FirstOrDefault(x => x.BuocId == buoc.Id && x.LenhTuongTacId == LenhTuongTac.Id); int hienNguoiNhan = 0; if (buocLenhTuongTac != null) { var buocLenhGroup = _context.VB_QT_BuocLenhGroupRole.FirstOrDefault(x => x.GroupRoleId == options.GroupRoleId && x.BuocLenhTuongTacId == buocLenhTuongTac.Id); hienNguoiNhan = CheckNguoiNhan.DuocHienThiNguoiNhan(_context, options.GroupRoleId, buocLenhGroup.Id); } switch (hienNguoiNhan) { #region Toàn công ty case 0: var listNsAll = await _context.Sys_Dm_User.Select(a => new { UserId = a.Id, a.FullName }).ToListAsync(); return(new ObjectResult(new { error = 0, data = listNsAll })); #endregion #region Công ty mẹ case 1: var listNsCTM = await _context.Sys_Dm_User.Where(x => x.CompanyId == 1).Select(a => new { UserId = a.Id, a.FullName }).ToListAsync(); return(new ObjectResult(new { error = 0, data = listNsCTM })); #endregion #region Công ty hiện tại case 2: var listNsCurrent = await _context.Sys_Dm_User.Where(x => x.CompanyId == user.CompanyId).Select(a => new { UserId = a.Id, a.FullName }).ToListAsync(); return(new ObjectResult(new { error = 0, data = listNsCurrent })); #endregion #region Phòng ban case 3: int DepId = 0; var room = await _context.Sys_Dm_Department.FindAsync(user.DepartmentId); if (room.ParentId == null) { DepId = room.Id; } else { DepId = room.ParentId ?? 0; } var listPb = _context.Sys_Dm_Department.Where(x => x.ParentId == DepId).Select(c => c.Id); var listNsPB = await _context.Sys_Dm_User.Where(x => listPb.Contains(x.DepartmentId ?? 0) || x.DepartmentId == DepId).Select(a => new { UserId = a.Id, a.FullName }).ToListAsync(); return(new ObjectResult(new { error = 0, data = listNsPB })); #endregion #region Tổ case 4: var listNsTo = await _context.Sys_Dm_User.Where(x => x.DepartmentId == user.DepartmentId).Select(a => new { UserId = a.Id, a.FullName }).ToListAsync(); return(new ObjectResult(new { error = 0, data = listNsTo })); #endregion #region Chỉ trưởng phòng case 7: var listNsInPB = await _context.Sys_Dm_User.Where(x => x.ParentDepartId == user.ParentDepartId).Select(a => a.Id).ToListAsync(); var tps = await(from b in _context.Sys_Cog_UsersGroup join c in _context.Sys_Dm_GroupRole on b.GroupRoleId equals c.Id join a in _context.Sys_Dm_User on b.UserId equals a.Id where listNsInPB.Contains(b.UserId) && c.IsAdminDep == true select new { b.UserId, a.FullName }).ToListAsync(); return(new ObjectResult(new { error = 0, data = tps })); #endregion default: var listNsDef = await _context.Sys_Dm_User.Where(x => x.DepartmentId == user.DepartmentId).Select(a => new { UserId = a.Id, a.FullName }).ToListAsync(); return(new ObjectResult(new { error = 0, data = listNsDef })); } } catch (Exception ex) { return(new ObjectResult(new { error = 1 })); } }
public async Task <IActionResult> r2addObjUnitCode() { try { var model = JsonConvert.DeserializeObject <VB_QT_VanBanMoiSoHoa>(Request.Form["model"]); VB_QT_VanBanMoiSoHoa objvb = new VB_QT_VanBanMoiSoHoa(); RequestToken token = CommonData.GetDataFromToken(User); var user = await _context.Sys_Dm_User.FindAsync(token.UserID); var userNguoiKy = await _context.Sys_Dm_User.FirstOrDefaultAsync(x => x.Id == model.NguoiKyId); if (model != null) { objvb.Id = Helper.GenKey(); objvb.CompanyId = user.CompanyId ?? 0; objvb.DepartmentId = user.DepartmentId ?? 0; objvb.TenNguoiKy = userNguoiKy.FullName; objvb.LinhVucId = model.LinhVucId; objvb.LoaiVanBanId = model.LoaiVanBanId; objvb.SoKyHieu = model.SoKyHieu; objvb.NoiBanHanh = model.NoiBanHanh; objvb.NgayBanHanh = model.NgayBanHanh; objvb.TuKhoa = model.TuKhoa; objvb.SoTrang = model.SoTrang; objvb.SoTrang = model.SoTrang; objvb.TenNguoiTao = user.FullName; objvb.CreateDate = DateTime.Now; objvb.UserCreateId = token.UserID; objvb.TrichYeu = model.TrichYeu; _context.VB_QT_VanBanMoiSoHoa.Add(objvb); } VB_QT_LuanChuyenVanBan lcvb = LuanChuyenVanBan.r2AddLuanChuyenVanBan(objvb.Id, token.UserID, user.FullName, token.UserID, user.FullName, "", "", false, null, null, 1, "VB_MOISOHOA", DateTime.Now, false, null, "VB0101", "VB0101", user.PositionName, user.PositionName, user.DepartmentName, user.DepartmentName); _context.VB_QT_LuanChuyenVanBan.Add(lcvb); if (Request.Form.Files.Count != 0) { foreach (var item in Request.Form.Files) { VB_QT_FileVBMoiSoHoa obj = new VB_QT_FileVBMoiSoHoa(); var file = item; var folderName = Path.Combine("Resources", "VanBan"); var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (!Directory.Exists(pathToSave)) { Directory.CreateDirectory(pathToSave); } if (model != null) { if (file.Length > 0) { var fileName = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss")).ToString() + ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var fullPath = Path.Combine(pathToSave, fileName); var dbPath = Path.Combine(folderName, fileName); obj.Path = dbPath; using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } } } obj.Name = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); obj.VbMoiSoHoaId = objvb.Id; obj.Size = file.Length; obj.Type = 1; _context.VB_QT_FileVBMoiSoHoa.Add(obj); } } await _context.SaveChangesAsync(); return(new ObjectResult(new { error = 0, ms = "" }));; } catch (Exception ex) { var result = new OkObjectResult(new { error = 1, ms = "Lỗi khi thêm mới UnitCode, vui lòng kiểm tra lại!" }); return(result); } }
public AccessToken GetAccessToken(RequestToken requestToken, string verifier) { return Consumer.GetAccessToken( verifier, requestToken, "https://api.twitter.com/oauth/access_token", "http://twitter.com/"); }
/// <summary> /// Requests an Access Token from the OAuth Service Provider. /// </summary> /// <remarks> /// An Access Token can only be created if a Request Token has been received, /// and that the Request Token has been authorized by the end-user. /// </remarks> /// <param name="token">The Request Token to upgrade.</param> /// <returns>A populated AccessToken.</returns> public AccessToken GetAccessToken(RequestToken token) { if (SignatureType == SignatureMethod.RsaSha1 && RsaCertificate == null) throw new RequiredPropertyNotSetException(Strings.ExRsaCertificateRequired); return GetAccessToken(AccessTokenUrl, token, ConsumerKey, ConsumerSecret, RsaCertificate, SignatureType, TokenRequestFormat); }
public string BuildUserAuthorizationURL(RequestToken reqToken) { return Consumer.BuildUserAuthorizationURL("https://api.twitter.com/oauth/authorize", reqToken); }
/// <summary> /// Upgrade a Request Token to an Access Token. /// </summary> /// <param name="uri">Access token URL.</param> /// <param name="token">RequestToken to upgrade.</param> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="sigMethod">The signature signing method.</param> /// <param name="mode">The HTTP connection and argument format to use.</param> /// <param name="rsaCert">The X509 certificate containing the private key used for RSA-SHA1.</param> /// <returns>A populated AccessToken.</returns> static AccessToken GetAccessToken(Uri uri, RequestToken token, string consumerKey, string consumerSecret, X509Certificate2 rsaCert, SignatureMethod sigMethod, AuthenticationMethod mode) { NameValueCollection nvc = TokenArgs(uri, null, consumerKey, consumerSecret, token.Key, token.Secret, rsaCert, sigMethod, AuthenticationMethodToString(mode)); WebResponse response = Request(uri, nvc, mode); NameValueCollection rparams = FormatResponse(response); return new AccessToken(rparams); }
public async Task <ActionResult <IEnumerable <VB_QT_VanBanMoiSoHoa> > > r2AddQTChuyenXuLy(LuanChuyenVbUser luanChuyenVbUser) { try { RequestToken token = CommonData.GetDataFromToken(User); var user = await _context.Sys_Dm_User.FindAsync(token.UserID); var userNCD = await _context.Sys_Dm_User.FindAsync(luanChuyenVbUser.UserNhan.NguoiChiDaoId); var userNXL = await _context.Sys_Dm_User.FindAsync(luanChuyenVbUser.UserNhan.NguoiXuLyId); var userNDXL = await _context.Sys_Dm_User.FindAsync(luanChuyenVbUser.UserNhan.NguoiDXuLyId); var userNNDB = await _context.Sys_Dm_User.FindAsync(luanChuyenVbUser.UserNhan.NguoiNDBId); var qtLuanChuyenVb = _context.VB_QT_LuanChuyenVanBan.Where(x => x.VbMoiSoHoaId == luanChuyenVbUser.VB_QT_LuanChuyenVanBan.VbMoiSoHoaId && x.NguoiNhanId == luanChuyenVbUser.VB_QT_LuanChuyenVanBan.NguoiGuiId && x.MenuNhanId == luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MenuGuiId).OrderByDescending(x => x.ThoiGianGui).Take(1); if (luanChuyenVbUser.UserNhan.NguoiChiDaoId != null) { VB_QT_LuanChuyenVanBan lcvb = LuanChuyenVanBan.r2AddLuanChuyenVanBan( luanChuyenVbUser.VB_QT_LuanChuyenVanBan.VbMoiSoHoaId, luanChuyenVbUser.UserNhan.NguoiChiDaoId, luanChuyenVbUser.UserNhan.TenNguoiChiDao, token.UserID, user.FullName, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.TieuDe, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.NoiDung, false, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.HanXuLy, null, 5, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MaLenh, null, false, qtLuanChuyenVb.FirstOrDefault().Id, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MenuGuiId, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MenuNhanId, userNCD.PositionName, user.PositionName, userNCD.DepartmentName, user.DepartmentName); _context.VB_QT_LuanChuyenVanBan.Add(lcvb); } if (luanChuyenVbUser.UserNhan.NguoiXuLyId != null) { VB_QT_LuanChuyenVanBan lcvb = LuanChuyenVanBan.r2AddLuanChuyenVanBan( luanChuyenVbUser.VB_QT_LuanChuyenVanBan.VbMoiSoHoaId, luanChuyenVbUser.UserNhan.NguoiXuLyId, luanChuyenVbUser.UserNhan.TenNguoiXuLy, token.UserID, user.FullName, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.TieuDe, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.NoiDung, false, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.HanXuLy, null, 6, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MaLenh, null, false, qtLuanChuyenVb.FirstOrDefault().Id, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MenuGuiId, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MenuNhanId, userNXL.PositionName, user.PositionName, userNXL.DepartmentName, user.DepartmentName); _context.VB_QT_LuanChuyenVanBan.Add(lcvb); } if (luanChuyenVbUser.UserNhan.NguoiDXuLyId != null) { VB_QT_LuanChuyenVanBan lcvb = LuanChuyenVanBan.r2AddLuanChuyenVanBan( luanChuyenVbUser.VB_QT_LuanChuyenVanBan.VbMoiSoHoaId, luanChuyenVbUser.UserNhan.NguoiDXuLyId, luanChuyenVbUser.UserNhan.TenNguoiDXuLy, token.UserID, user.FullName, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.TieuDe, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.NoiDung, false, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.HanXuLy, null, 7, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MaLenh, null, false, qtLuanChuyenVb.FirstOrDefault().Id, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MenuGuiId, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MenuNhanId, userNXL.PositionName, user.PositionName, userNXL.DepartmentName, user.DepartmentName); _context.VB_QT_LuanChuyenVanBan.Add(lcvb); } if (luanChuyenVbUser.UserNhan.NguoiDXuLyId != null) { VB_QT_LuanChuyenVanBan lcvb = LuanChuyenVanBan.r2AddLuanChuyenVanBan( luanChuyenVbUser.VB_QT_LuanChuyenVanBan.VbMoiSoHoaId, luanChuyenVbUser.UserNhan.NguoiNDBId, luanChuyenVbUser.UserNhan.TenNguoiNDB, token.UserID, user.FullName, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.TieuDe, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.NoiDung, false, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.HanXuLy, null, 8, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MaLenh, null, false, qtLuanChuyenVb.FirstOrDefault().Id, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MenuGuiId, luanChuyenVbUser.VB_QT_LuanChuyenVanBan.MenuNhanId, userNNDB.PositionName, user.PositionName, userNNDB.DepartmentName, user.DepartmentName); _context.VB_QT_LuanChuyenVanBan.Add(lcvb); } await _context.SaveChangesAsync(); return(new ObjectResult(new { error = 0 })); } catch (Exception ex) { return(new ObjectResult(new { error = 1 })); } }
/// <summary> /// Get the OAuth Access Token from the current OpenID response. /// </summary> /// <returns>A populated AccessToken.</returns> public AccessToken GetAccessToken() { NameValueCollection request = Parent.RequestArguments; NameValueCollection ds = Utility.GetExtNamespaceAliases(request); if (ds[NamespaceUri.AbsoluteUri] == null) return null; string p = ds[NamespaceUri.AbsoluteUri]; string _pre = "openid." + p + "."; NameValueCollection rta = new NameValueCollection(); rta["oauth_token"] = request[_pre + "request_token"]; rta["scope"] = request[_pre + "scope"]; RequestToken requestToken = new RequestToken(rta); return OAuthClient.GetAccessToken(requestToken); }
/// <summary> /// This method should be called once you have received the verifier from /// Evernote. It will populate a EvernoteCredentials object with all the /// information you need to authenticate to Evernote as this user /// </summary> /// <remarks> /// This is an asynchronous method /// </remarks> /// <param name="oauth_verifier">The verifier passed in via the QueryString to your endpoint</param> /// <param name="token">The token used to request the authorization - this should be persisted from the call to GetRequestToken</param> /// <returns></returns> public EvernoteCredentials ParseAccessToken(string oauth_verifier, RequestToken token) { return(Task.Run(() => AsyncEvernoteAuthorizer.ParseAccessToken(oauth_verifier, token)).Result); }
private async Task <AccessToken> ObtainAccessTokenAsync(string consumerKey, string consumerSecret, RequestToken token, string verifier) { // https://dev.twitter.com/docs/api/1/post/oauth/access_token _logger.WriteVerbose("ObtainAccessToken"); string nonce = Guid.NewGuid().ToString("N"); var authorizationParts = new SortedDictionary <string, string> { { "oauth_consumer_key", consumerKey }, { "oauth_nonce", nonce }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_token", token.Token }, { "oauth_timestamp", GenerateTimeStamp() }, { "oauth_verifier", verifier }, { "oauth_version", "1.0" }, }; var parameterBuilder = new StringBuilder(); foreach (var authorizationKey in authorizationParts) { parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(authorizationKey.Key), Uri.EscapeDataString(authorizationKey.Value)); } parameterBuilder.Length--; string parameterString = parameterBuilder.ToString(); var canonicalizedRequestBuilder = new StringBuilder(); canonicalizedRequestBuilder.Append(HttpMethod.Post.Method); canonicalizedRequestBuilder.Append("&"); canonicalizedRequestBuilder.Append(Uri.EscapeDataString(AccessTokenEndpoint)); canonicalizedRequestBuilder.Append("&"); canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString)); string signature = ComputeSignature(consumerSecret, token.TokenSecret, canonicalizedRequestBuilder.ToString()); authorizationParts.Add("oauth_signature", signature); authorizationParts.Remove("oauth_verifier"); var authorizationHeaderBuilder = new StringBuilder(); authorizationHeaderBuilder.Append("OAuth "); foreach (var authorizationPart in authorizationParts) { authorizationHeaderBuilder.AppendFormat( "{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value)); } authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2; var request = new HttpRequestMessage(HttpMethod.Post, AccessTokenEndpoint); request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString()); var formPairs = new Dictionary <string, string>() { { "oauth_verifier", verifier }, }; request.Content = new FormUrlEncodedContent(formPairs); HttpResponseMessage response = await _httpClient.SendAsync(request, Context.RequestAborted); if (!response.IsSuccessStatusCode) { _logger.WriteError("AccessToken request failed with a status code of " + response.StatusCode); response.EnsureSuccessStatusCode(); // throw } string responseText = await response.Content.ReadAsStringAsync(); IFormCollection responseParameters = FormHelpers.ParseForm(responseText); return(new AccessToken { Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), UserId = Uri.UnescapeDataString(responseParameters["user_id"]), ScreenName = Uri.UnescapeDataString(responseParameters["screen_name"]) }); }
private async Task <AccessToken> ObtainAccessToken(string consumerKey, string consumerSecret, RequestToken token, string verifier) { _logger.WriteVerbose("ObtainAccessToken"); var obtainAccessTokenRequest = CreateTwitterWebRequest(AccessTokenEndpoint); var nonce = Guid.NewGuid().ToString("N"); var authorizationParts = new SortedDictionary <string, string> { { "oauth_consumer_key", consumerKey }, { "oauth_nonce", nonce }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_token", token.Token }, { "oauth_timestamp", GenerateTimeStamp() }, { "oauth_verifier", verifier }, { "oauth_version", "1.0" }, }; var parameterBuilder = new StringBuilder(); foreach (var authorizationKey in authorizationParts) { parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(authorizationKey.Key), Uri.EscapeDataString(authorizationKey.Value)); } parameterBuilder.Length--; var parameterString = parameterBuilder.ToString(); var canonicalizedRequestBuilder = new StringBuilder(); canonicalizedRequestBuilder.Append(obtainAccessTokenRequest.Method); canonicalizedRequestBuilder.Append("&"); canonicalizedRequestBuilder.Append(Uri.EscapeDataString(obtainAccessTokenRequest.RequestUri.ToString())); canonicalizedRequestBuilder.Append("&"); canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString)); var signature = ComputeSignature(consumerSecret, token.TokenSecret, canonicalizedRequestBuilder.ToString()); authorizationParts.Add("oauth_signature", signature); authorizationParts.Remove("oauth_verifier"); var authorizationHeaderBuilder = new StringBuilder(); authorizationHeaderBuilder.Append("OAuth "); foreach (var authorizationPart in authorizationParts) { authorizationHeaderBuilder.AppendFormat( "{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value)); } authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2; obtainAccessTokenRequest.Headers.Add("Authorization", authorizationHeaderBuilder.ToString()); var bodyData = "oauth_verifier=" + Uri.EscapeDataString(verifier); obtainAccessTokenRequest.ContentLength = bodyData.Length; using (var bodyStream = new StreamWriter(obtainAccessTokenRequest.GetRequestStream())) { bodyStream.Write(bodyData); } // TODO : Error handling try { var obtainAccessTokenResponse = await obtainAccessTokenRequest.GetResponseAsync() as HttpWebResponse; string responseText; using (var reader = new StreamReader(obtainAccessTokenResponse.GetResponseStream())) { responseText = await reader.ReadToEndAsync(); responseText = responseText.Replace('+', ' '); } var responseParameters = responseText.Split('&').Select(responseParameter => responseParameter.Split('=')).ToDictionary(brokenParameter => brokenParameter[0], brokenParameter => brokenParameter[1]); return(new AccessToken { Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), UserId = Uri.UnescapeDataString(responseParameters["user_id"]), ScreenName = Uri.UnescapeDataString(responseParameters["screen_name"]) }); } catch (WebException ex) { using (WebResponse response = ex.Response) { var httpResponse = (HttpWebResponse)response; using (Stream responseStream = response.GetResponseStream()) using (var reader = new StreamReader(responseStream)) { string text = reader.ReadToEnd(); _logger.WriteError("AccessToken request failed with a status code of " + httpResponse.StatusCode + " - " + text); } } throw; } return(null); }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { IReadableStringCollection query = Request.Query; string protectedRequestToken = Request.Cookies[StateCookie]; RequestToken requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken); if (requestToken == null) { _logger.WriteWarning("Invalid state"); return(null); } properties = requestToken.Properties; string returnedToken = query.Get("oauth_token"); if (string.IsNullOrWhiteSpace(returnedToken)) { _logger.WriteWarning("Missing oauth_token"); return(new AuthenticationTicket(null, properties)); } if (returnedToken != requestToken.Token) { _logger.WriteWarning("Unmatched token"); return(new AuthenticationTicket(null, properties)); } string oauthVerifier = query.Get("oauth_verifier"); if (string.IsNullOrWhiteSpace(oauthVerifier)) { _logger.WriteWarning("Missing or blank oauth_verifier"); return(new AuthenticationTicket(null, properties)); } AccessToken accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken, oauthVerifier); var context = new TwitterAuthenticatedContext(Context, accessToken.UserId, accessToken.ScreenName, accessToken.Token, accessToken.TokenSecret); context.Identity = new ClaimsIdentity( new[] { new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim(ClaimTypes.Name, accessToken.ScreenName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("urn:twitter:userid", accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("urn:twitter:screenname", accessToken.ScreenName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType) }, Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); context.Properties = requestToken.Properties; var cookieOptions = new CookieOptions { HttpOnly = true, Secure = Request.IsSecure }; Response.Cookies.Delete(StateCookie, cookieOptions); await Options.Notifications.Authenticated(context); return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception ex) { _logger.WriteError("Authentication failed", ex); return(new AuthenticationTicket(null, properties)); } }
/// <summary> /// Returns a URL that you can redirect the user to on the Evernote site that /// will prompt them to authroize your app. Once they do this, they will /// be redirected to callbackUri with the oauth_validator parameter /// </summary> /// <param name="callbackUri">The end point you plan on using to call ParseAccessToken</param> /// <returns></returns> public string BuildAuthorizeUrl(RequestToken token) { return(AsyncEvernoteAuthorizer.BuildAuthorizeUrl(token)); }
public void SaveRequestToken(RequestToken requestToken) { _requestToken = requestToken; }