public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { FirebaseManager.Configure(); App.Initialize(); #if ENABLE_TEST_CLOUD Xamarin.Calabash.Start(); #endif GoogleUserInfo userInfo = GoogleUserInfo.ReadFromDevice().Result; if (userInfo != null) { var mainStoryboard = UIStoryboard.FromName("Main", null); var tabBarController = mainStoryboard.InstantiateViewController("tabViewController") as TabBarController; var navigationController = tabBarController.ViewControllers[0] as UINavigationController; var homeViewController = navigationController.ViewControllers[0] as HomeViewController; homeViewController.ViewModel = new ViewModels.HomeViewModel(userInfo.GivenName); // Set the tab bar controller as root Window.RootViewController = tabBarController; } return(true); }
public async Task <LoginResult> AuthenticateAsync(GoogleAccount account, RemoteUser user) { bool validationResult = Task.Run(() => this.ValidateAsync(account.Token)).GetAwaiter().GetResult(); if (!validationResult) { return(new LoginResult { Status = false, Message = Resources.AccessIsDenied }); } var gUser = new GoogleUserInfo { Email = account.Email, Name = account.Name }; var result = await GoogleSignIn.SignInAsync(this.Tenant, account.Email, account.OfficeId, account.Name, account.Token, user.Browser, user.IpAddress, account.Culture).ConfigureAwait(false); if (result.Status) { if (!await Registrations.HasAccountAsync(this.Tenant, account.Email).ConfigureAwait(false)) { string template = "~/Tenants/{tenant}/Areas/Frapid.Account/EmailTemplates/welcome-email-other.html"; var welcomeEmail = new WelcomeEmail(gUser, template, ProviderName); await welcomeEmail.SendAsync(this.Tenant).ConfigureAwait(false); } } return(result); }
public async Task <LoginResult> AuthenticateAsync(GoogleAccount account, RemoteUser user) { bool validationResult = Task.Run(() => ValidateAsync(account.Token)).Result; if (!validationResult) { return(new LoginResult { Status = false, Message = "Access is denied" }); } var gUser = new GoogleUserInfo { Email = account.Email, Name = account.Name }; var result = GoogleSignIn.SignIn(account.Email, account.OfficeId, account.Name, account.Token, user.Browser, user.IpAddress, account.Culture); if (result.Status) { if (!Registrations.HasAccount(account.Email)) { string template = "~/Catalogs/{catalog}/Areas/Frapid.Account/EmailTemplates/welcome-email-other.html"; var welcomeEmail = new WelcomeEmail(gUser, template, ProviderName); await welcomeEmail.SendAsync(); } } return(result); }
async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e) { var authenticator = sender as OAuth2Authenticator; GoogleUserInfo user = null; if (authenticator != null) { authenticator.Completed -= OnAuthCompleted; authenticator.Error -= OnAuthError; } if (e.IsAuthenticated) { // If the user is authenticated, request their basic user data from Google var request = new OAuth2Request("GET", new Uri(Constants.UserInfoUrl), null, e.Account); var response = await request.GetResponseAsync(); if (response != null) { // Deserialize the data and store it in the account store // The users email address will be used to identify data in SimpleDB string userJson = await response.GetResponseTextAsync(); //await DisplayAlert("JSON", userJson, "OK"); debug user = JsonConvert.DeserializeObject <GoogleUserInfo>(userJson); } if (account != null) { store.Delete(account, Constants.AppName); } CreateAccountGoogleAuth(user); } }
protected void Page_Load(object sender, EventArgs e) { ILocalizedTextService textService = ApplicationContext.Services.TextService; // Get the state from the query string string state = Request.QueryString["state"]; // Check whether the state is present if (string.IsNullOrWhiteSpace(state)) { //Ouput an error message _content.Text += textService.Localize("pieman", new [] { "noAccess" }); return; } // Get the session value // Has the session expire? if (!(Session["PieMan_" + state] is string session)) { //Ouput an error message _content.Text += textService.Localize("pieman", new [] { "sorrySessionExpired" }); return; } // Get the refresh token from the query string (kinda bad practice though) string refreshToken = Request.QueryString["token"]; // Do we have a refresh token? if (string.IsNullOrWhiteSpace(refreshToken)) { //Ouput an error message _content.Text += textService.Localize("pieman", new [] { "somethingWentWrong" }); return; } // Initalize a new instance of the GoogleService class GoogleService service = GoogleService.CreateFromRefreshToken(Config.ClientIdFromPropertyEditor, Config.ClientSecretFromPropertyEditor, refreshToken); try { //Get the authenticated user GoogleUserInfo user = service.GetUserInfo().Body; //Set the refresh token in our config Config.RefreshTokenFromPropertyEditor = refreshToken; //Ouput some info about the user _content.Text = "Hi there " + user.Name + ". We have saved your information to a config file, so Umbraco can pull stats from your Google Analytics account."; _content.Text += "<br /><br />Close this window and go grab a piping hot serve of stats - you'll need to reopen the settings panel and select an account and profile."; } catch { //Ouput an error message _content.Text += textService.Localize("pieman", new [] { "somethingWentWrong" }); } // Clear the session state Session.Remove("PieMan_" + state); }
private static string GetGooglePictureUrl(string accessToken) { string uri = $"https://www.googleapis.com/oauth2/v2/userinfo?alt=json&access_token={accessToken}"; GoogleUserInfo googleUserInfo = WebRequestHelper.Get <GoogleUserInfo>(uri); return(googleUserInfo.picture); }
protected void Page_Load(object sender, EventArgs e) { // Get the state from the query string string state = Request.QueryString["state"]; // Check whether the state is present if (String.IsNullOrWhiteSpace(state)) { //Ouput an error message Content.Text += "No state specified."; return; } // Get the session value string session = Session["Analytics_" + state] as string; // Has the session expire? if (session == null) { //Ouput an error message Content.Text += "Sorry - your session has most likely expired."; return; } // Get the refresh token from the query string (kinda bad practice though) string refreshToken = Request.QueryString["token"]; // Do we have a refresh token? if (String.IsNullOrWhiteSpace(refreshToken)) { //Ouput an error message Content.Text += "Okay. Something went wrong."; return; } // Initalize a new instance of the GoogleService class GoogleService service = GoogleService.CreateFromRequestToken(AnalyticsConfig.ClientId, AnalyticsConfig.ClientSecret, refreshToken); try { //Get the authenticated user GoogleUserInfo user = service.GetUserInfo(); //Set the refresh token in our config AnalyticsConfig.RefreshToken = refreshToken; //Ouput some info about the user Content.Text = "Hi there " + user.Name + ". We have saved your information to a config file, so Umbraco can pull stats from your Analytics account."; } catch { //Ouput an error message Content.Text += "Okay. Something went wrong."; } // Clear the session state Session.Remove("Analytics_" + state); }
/// <summary> /// Tries to login with Google Auth /// </summary> public void Login() { string code = Request.QueryString["code"]; string error = Request.QueryString["error"]; string baseUrl = System.Configuration.ConfigurationManager.AppSettings["baseUrl"]; GoogleOAuthClient oauth = new GoogleOAuthClient { ClientId = "clientId", ClientSecret = "clientSecret", RedirectUri = baseUrl + "/umbraco/surface/auth/login" }; // Handle if an error occurs during the Google authentication (eg. if the user cancels the login) if (!String.IsNullOrWhiteSpace(error)) { return; } // Handle the state when the user is redirected back to our page after a successful login with the Google API if (!String.IsNullOrWhiteSpace(code)) { MemberServiceController memberService = new MemberServiceController(); // Exchange the authorization code for an access token GoogleAccessTokenResponse response = oauth.GetAccessTokenFromAuthorizationCode(code); string accessToken = response.AccessToken; // Initialize a new instance of the GoogleService class so we can make calls to the API GoogleService service = GoogleService.CreateFromAccessToken(accessToken); // Make a call to the API to get information about the authenticated user GoogleUserInfo user = service.GetUserInfo(); //Checks whether the user is logging in with a emakina account if (memberService.CreateNewMember(user.GivenName, user.FamilyName, user.Email, user.Id, user.Picture)) { FormsAuthentication.SetAuthCookie("google_" + user.Id, false); Response.Redirect("/"); } else { return; } } else { string redirect = (Request.QueryString["redirect"] ?? "/"); // Set the state (a unique/random value) string state = Guid.NewGuid().ToString(); Session["Google_" + state] = redirect; // Construct the authorization URL string authorizationUrl = oauth.GetAuthorizationUrl(state, GoogleScopes.Email + GoogleScopes.Profile, GoogleAccessType.Online, GoogleApprovalPrompt.Force); // Redirect the user to the OAuth dialog Response.Redirect(authorizationUrl); } }
public async Task <TokenResponse> Handle(Commands request, CancellationToken cancellationToken) { var user = new AppUser(); var googleUser = new GoogleUserInfo(); var facebookUser = new FacebookUserInfoResult(); if (request.Provider.Equals("google")) { googleUser = await _externalLogin.GetGoogleInfoasync(request.AccessToken); if (googleUser == null) { throw new RestException(HttpStatusCode.BadRequest, new { msg = "Invalid Token" }); } user = _mapper.Map <AppUser>(googleUser); } else if (request.Provider.Equals("facebook")) { facebookUser = await _externalLogin.GetFacebookInfoasync(request.AccessToken); if (facebookUser == null) { throw new RestException(HttpStatusCode.BadRequest, new { msg = "Invalid Token" }); } user = _mapper.Map <AppUser>(facebookUser); } else { throw new RestException(HttpStatusCode.BadRequest, new { msg = "Invalid Provider" }); } var newUser = await _userManager.FindByIdAsync(user.Id); if (newUser == null) { var result = await _userManager.CreateAsync(user); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "user"); var newDto = _mapper.Map <UserDto>(user); newDto.ImgUrl = user.ImgUrl; return(new TokenResponse(_jwtGenerator.CreateToken(user), newDto)); } } var userDto = _mapper.Map <UserDto>(user); userDto.ImgUrl = user.ImgUrl; return(new TokenResponse(_jwtGenerator.CreateToken(user), userDto)); }
public async Task <GoogleUserInfo> GetUserInfo(string accessToken) { var client = _clientFactory.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, "https://www.googleapis.com/oauth2/v2/userinfo"); request.Headers.Add("Authorization", $"Bearer {accessToken}"); var response = await client.SendAsync(request); string jsonResult = await response.Content.ReadAsStringAsync(); GoogleUserInfo userInfo = JsonConvert.DeserializeObject <GoogleUserInfo>(jsonResult); return(userInfo); }
private void OnGoogleLoginButtonClicked(object sender, EventArgs e) { var googleToken = GoogleOAuthToken.ReadFromDevice().Result; var userInfo = GoogleUserInfo.ReadFromDevice().Result; if (googleToken == null || userInfo == null) { var authenticator = Auth.GetAuthenticator(); var viewController = authenticator.GetUI(); PresentViewController(viewController, true, null); } else { PerformSegueToHome(userInfo.GivenName); } }
private User UpdateUserWithGoogleAuth(IdentityProviderAuthResponse auth) { GoogleUserInfo userInfo = _googleAPIs.GetUserInfo(auth.AccessToken).Result; string newAuthCode = AuthCodeUtility.GenerateAuthCode(); var updatedUser = _collection.FindOneAndUpdate( new FilterDefinitionBuilder <User>().Where(x => x.EmailAddress == auth.EmailAddress), new UpdateDefinitionBuilder <User>().Set(x => x.GoogleAuth, auth) .Set(x => x.FirstName, userInfo.FirstName) .Set(x => x.LastName, userInfo.LastName) .Set(x => x.AuthCode, newAuthCode) ); updatedUser.GoogleAuth = auth; updatedUser.AuthCode = newAuthCode; return(updatedUser); }
public async Task <FirebaseUserInfo> AuthenticateUser(GoogleUserInfo googleUserInfo) { if (CrossConnectivity.Current.IsConnected) { var response = await client.GetAsync($"authenticate/{googleUserInfo.Email}"); if (response.IsSuccessStatusCode) { string id = await response.Content.ReadAsStringAsync(); return(new FirebaseUserInfo() { Id = id }); } } return(null); }
private void LogOut() { FirebaseManager.Auth.SignOut(out NSError error); if (error == null) { GoogleUserInfo.RemoveFromDevice(); GoogleOAuthToken.RemoveFromDevice(); FirebaseUserInfo.RemoveFromDevice(); var rootNavController = Storyboard.InstantiateViewController("navLoginController") as UINavigationController; var appDelegate = UIApplication.SharedApplication.Delegate as AppDelegate; appDelegate.Window.RootViewController = rootNavController; } else { DisplayErrorMessage("An error occurred while logging you out."); } }
private User InsertUserWithGoogleAuth(IdentityProviderAuthResponse auth) { GoogleUserInfo userinfo = _googleAPIs.GetUserInfo(auth.AccessToken).Result; var newUser = new User(); newUser.FirstName = userinfo.FirstName; newUser.LastName = userinfo.LastName; newUser.Roles = new List <string>() { RolesEnum.None.ToString() }; newUser.EmailAddress = userinfo.Email; newUser.GoogleAuth = auth; newUser.AuthCode = AuthCodeUtility.GenerateAuthCode(); _collection.InsertOne(newUser); return(newUser); }
private async Task LoadUserData () { if (IsBusy) return; IsBusy = true; // Since we have an access token, we may as well go out to google and find out who the hell just logged in. if (App.Current.Properties.TryGetValue ("access_token", out accessToken)) { if (accessToken.ToString ().Length > 0) { string url = @"https://www.googleapis.com/oauth2/v1/userinfo?alt=json"; var httpClient = new HttpClient(new NativeMessageHandler()); var authHeader = new AuthenticationHeaderValue ("Bearer", accessToken.ToString()); httpClient.DefaultRequestHeaders.Authorization = authHeader; Task<string> apiWebRequest = httpClient.GetStringAsync(url); // async method! string apiResponse = await apiWebRequest; try { googleUserInfo = JsonConvert.DeserializeObject<GoogleUserInfo> (apiResponse); } catch (Exception ex) { var temp = ex; } } } IsBusy = false; try { // Change the logout button to be super customized. Sort of. btnLogout.Text = "Log Out " + googleUserInfo.given_name; } catch { } return; }
async void CreateAccountGoogleAuth(GoogleUserInfo googleUser) { User user = new User(googleUser.given_name, googleUser.family_name, googleUser.email); HttpClientRequests requests = new HttpClientRequests(googleUser.email, "LOLILOL12"); //todo check how to deal with password //I try to login to check if the account is already sign up Login(requests); //if I'm not signed up I sign up var response = await requests.SignUp(user); if (response == System.Net.HttpStatusCode.OK) { // I login as soon as i have created the account on the server Login(requests); } else { await DisplayAlert("Sign up failed", response.ToString(), "KO"); } }
public async Task <GoogleUserInfo> GetGoogleData(string code) { var gmailAuth = new GmailAuth(); gmailAuth.client_id = "client_id"; gmailAuth.client_secret = "client_secret"; gmailAuth.auth_uri = "https://accounts.google.com/o/oauth2/auth"; gmailAuth.token_uri = "https://accounts.google.com/o/oauth2/token"; var domainName = "http://localhost:5000"; // var responseType="code"; // var scope="https://www.googleapis.com/auth/userinfo.profile"; gmailAuth.redirect_uri = $"{domainName}/home/getgoogledata/sign-in"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response; var objJson = new GmailAuthHelper().GetUrlEncodedContent(gmailAuth, code); response = await client.PostAsync(gmailAuth.token_uri, objJson); if (response.IsSuccessStatusCode) { var jsondata = response.Content.ReadAsStringAsync().Result; GoogleData mytoken = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject <GoogleData>(jsondata)); GoogleUserInfo userinfo = await GetUserDetails(mytoken.Access_token); return(userinfo); } else { return(null); } } }
private async Task <GoogleUserInfo> GetUserDetails(string access_token) { using (var client = new HttpClient()) { var userinfo_request_uri = "https://www.googleapis.com/oauth2/v2/userinfo"; var url = $"{userinfo_request_uri}?access_token={access_token}"; client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Clear(); HttpResponseMessage response; response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; GoogleUserInfo info = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject <GoogleUserInfo>(result)); return(info); } else { return(null); } } }
private bool InitInfoGoogleUser(ExternalLoginInfo loginInfo, string userId) { //bool result = false; googleUserInfo = new GoogleUserInfo(); var response = googleUserInfo.InitializeInfo(loginInfo); profile = new UserProfile { GivenName = response.FirstName, FamilyName = response.LastName, ExternalPic = response.Picture, UserId = userId, }; //if (Create(profile) != null) //{ // result = true; //} return(Create(profile) != null ? true : false); //return result; }
protected void Page_Load(object sender, EventArgs e) { //Get current user var currentUser = UmbracoContext.Current.Security.CurrentUser; //Check a user is logged into backoffice if (currentUser == null) { //Ouput an error message Content.Text += ui.Text("analytics", "noAccess"); return; } //Check the user has access to the analytics section //Prevents anyone with this URL to page from just hitting it if (!currentUser.AllowedSections.Contains("analytics")) { //Ouput an error message Content.Text += ui.Text("analytics", "noAccess"); return; } // Get the state from the query string string state = Request.QueryString["state"]; // Check whether the state is present if (String.IsNullOrWhiteSpace(state)) { //Ouput an error message Content.Text += ui.Text("analytics", "noStateSpecified"); return; } // Get the session value string session = Session["Analytics_" + state] as string; // Has the session expire? if (session == null) { //Ouput an error message Content.Text += ui.Text("analytics", "sorrySessionExpired"); return; } // Get the refresh token from the query string (kinda bad practice though) string refreshToken = Request.QueryString["token"]; // Do we have a refresh token? if (String.IsNullOrWhiteSpace(refreshToken)) { //Ouput an error message Content.Text += ui.Text("analytics", "somethingWentWrong"); return; } // Initalize a new instance of the GoogleService class GoogleService service = GoogleService.CreateFromRefreshToken(AnalyticsConfig.ClientId, AnalyticsConfig.ClientSecret, refreshToken); try { //Get the authenticated user GoogleUserInfo user = service.GetUserInfo(); //Set the refresh token in our config AnalyticsConfig.RefreshToken = refreshToken; //Ouput some info about the user //Using UmbracoUser (obsolete) - somehow it fails to compile when using Security.CurrentUser //ui.text requires OLD BusinessLogic User object type not shiny new one //Can we use another helper/library to get the translation text? var umbUser = new User(currentUser.Id); Content.Text = ui.Text("analytics", "informationSavedMessage", user.Name, umbUser); } catch { //Ouput an error message Content.Text += ui.Text("analytics", "somethingWentWrong"); } // Clear the session state Session.Remove("Analytics_" + state); }
public async Task <FirebaseUserInfo> AuthenticateUserWithFirebaseAsync(GoogleUserInfo googleUserInfo) { return(await DataStore.AuthenticateUser(googleUserInfo)); }
public Task <FirebaseUserInfo> AuthenticateUser(GoogleUserInfo googleUserInfo) { return(null); }
protected void Page_Load(object sender, EventArgs e) { Title = "Google OAuth"; Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; Feature = Request.QueryString["feature"]; if (AuthState != null) { NameValueCollection stateValue = Session["Skybrud.Social_" + AuthState] as NameValueCollection; if (stateValue != null) { Callback = stateValue["Callback"]; ContentTypeAlias = stateValue["ContentTypeAlias"]; PropertyAlias = stateValue["PropertyAlias"]; Feature = stateValue["Feature"]; } } // Get the prevalue options GoogleOAuthPreValueOptions options = GoogleOAuthPreValueOptions.Get(ContentTypeAlias, PropertyAlias); if (!options.IsValid) { Content.Text += "Hold on now! The options of the underlying prevalue editor isn't valid."; return; } // Configure the OAuth client based on the options of the prevalue options GoogleOAuthClient client = new GoogleOAuthClient { ClientId = options.ClientId, ClientSecret = options.ClientSecret, RedirectUri = options.RedirectUri }; // Session expired? if (AuthState != null && Session["Skybrud.Social_" + AuthState] == null) { Content.Text = "<div class=\"error\">Session expired?</div>"; return; } // Check whether an error response was received from Google if (AuthError != null) { Content.Text = "<div class=\"error\">Error: " + AuthErrorDescription + "</div>"; if (AuthState != null) { Session.Remove("Skybrud.Social:" + AuthState); } return; } string state; // Redirect the user to the Google login dialog if (AuthCode == null) { // Generate a new unique/random state state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["Skybrud.Social_" + state] = new NameValueCollection { { "Callback", Callback }, { "ContentTypeAlias", ContentTypeAlias }, { "PropertyAlias", PropertyAlias }, { "Feature", Feature } }; // Declare the scope GoogleScopeCollection defaultScope = new[] { GoogleScope.OpenId, GoogleScope.Email, GoogleScope.Profile }; string scope = options.Scope != null?string.Join(" ", options.Scope) : defaultScope.ToString(); // Construct the authorization URL string url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force); // Redirect the user Response.Redirect(url); return; } GoogleAccessTokenResponse info; try { info = client.GetAccessTokenFromAuthorizationCode(AuthCode); } catch (Exception ex) { Content.Text = "<div class=\"error\"><b>Unable to acquire access token</b><br />" + ex.Message + "</div>"; return; } try { // Initialize the Google service GoogleService service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken); // Get information about the authenticated user GoogleUserInfo user = service.GetUserInfo(); Content.Text += "<p>Hi <strong>" + user.Name + "</strong></p>"; Content.Text += "<p>Please wait while you're being redirected...</p>"; // Set the callback data GoogleOAuthData data = new GoogleOAuthData { Id = user.Id, Name = user.Name, Avatar = user.Picture, ClientId = client.ClientIdFull, ClientSecret = client.ClientSecret, RefreshToken = info.RefreshToken }; // Update the UI and close the popup window Page.ClientScript.RegisterClientScriptBlock(GetType(), "callback", String.Format( "self.opener." + Callback + "({0}); window.close();", data.Serialize() ), true); } catch (Exception ex) { Content.Text = "<div class=\"error\"><b>Unable to get user information</b><br />" + ex.Message + "</div>"; return; } }
/// <summary> /// Validate provided username and password when the grant_type is set to "password". /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { if (context.OwinContext.Request.Headers["Provider"] != null) { if (context.OwinContext.Request.Headers["Provider"].ToLower() == "facebook" && context.OwinContext.Request.Headers["access_token"] != null) { var accessToken = context.OwinContext.Request.Headers["access_token"]; var client = new RestClient("https://graph.facebook.com/"); var request = new RestRequest("me", Method.GET); request.AddQueryParameter("fields", "id,name,email,picture.width(2000).height(2000)"); request.AddQueryParameter("access_token", accessToken); var response = client.Execute(request); if (response.StatusCode == HttpStatusCode.OK) { var content = JObject.Parse(response.Content); var userInfo = new FacebookUserInfo() { id = content["id"].ToString() }; if (content["name"] != null) { userInfo.name = content["name"].ToString(); } if (content["email"] != null) { userInfo.email = content["email"].ToString(); } if (content["picture"]["data"]["url"] != null) { userInfo.avatar = content["picture"]["data"]["url"].ToString(); } PregnancyEntity connect = new PregnancyEntity(); preg_user user = connect.preg_user.Where(c => c.uid == userInfo.id && c.social_type_id == (int)SysConst.SocialTypes.facebook).FirstOrDefault(); if (user != null) { //user.email = userInfo.email; //user.first_name = userInfo.name; user.time_last_login = DateTime.Now; connect.SaveChanges(); } else { user = new preg_user(); user.uid = userInfo.id; user.email = userInfo.email; user.first_name = userInfo.name; user.avatar = userInfo.avatar; user.social_type_id = (int)SysConst.SocialTypes.facebook; user.time_created = DateTime.Now; connect.preg_user.Add(user); SysMethod.createAccountNop(user); connect.SaveChanges(); user = connect.preg_user.Where(c => c.uid == userInfo.id && c.social_type_id == (int)SysConst.SocialTypes.facebook).FirstOrDefault(); } preg_auth auth = connect.preg_auth.Where(c => c.user_id == user.id).FirstOrDefault(); if (auth == null) { auth = new preg_auth() { user_id = user.id }; connect.preg_auth.Add(auth); } auth.token = context.OwinContext.Request.Headers["access_token"]; connect.SaveChanges(); var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.social.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.user.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.dev.ToString())); identity.AddClaim(new Claim("id", user.id.ToString())); context.Validated(identity); } else { context.SetError("Invalid grant", SysConst.LOGIN_SOCIAL_FAILED); return; } } else if (context.OwinContext.Request.Headers["Provider"].ToLower() == "google" && context.OwinContext.Request.Headers["access_token"] != null) { var accessToken = context.OwinContext.Request.Headers["access_token"]; var client = new RestClient("https://www.googleapis.com/oauth2/v3/"); var request = new RestRequest("tokeninfo", Method.GET); request.AddQueryParameter("id_token", accessToken); var response = client.Execute(request); if (response.StatusCode == HttpStatusCode.OK) { var content = JObject.Parse(response.Content); var userInfo = new GoogleUserInfo() { sub = content["sub"].ToString() }; if (content["name"] != null) { userInfo.name = content["name"].ToString(); } if (content["email"] != null) { userInfo.email = content["email"].ToString(); } if (content["picture"] != null) { userInfo.picture = content["picture"].ToString(); } if (content["given_name"] != null) { userInfo.given_name = content["given_name"].ToString(); } if (content["family_name"] != null) { userInfo.family_name = content["family_name"].ToString(); } PregnancyEntity connect = new PregnancyEntity(); preg_user user = connect.preg_user.Where(c => c.uid == userInfo.sub && c.social_type_id == (int)SysConst.SocialTypes.google).FirstOrDefault(); if (user != null) { //user.email = userInfo.email; //user.first_name = userInfo.name; //user.avatar = userInfo.picture; user.time_last_login = DateTime.Now; connect.SaveChanges(); } else { user = new preg_user(); user.uid = userInfo.sub; user.email = userInfo.email; user.first_name = userInfo.name; user.avatar = userInfo.picture; user.social_type_id = (int)SysConst.SocialTypes.google; user.time_created = DateTime.Now; connect.preg_user.Add(user); SysMethod.createAccountNop(user); connect.SaveChanges(); user = connect.preg_user.Where(c => c.uid == userInfo.sub && c.social_type_id == (int)SysConst.SocialTypes.google).FirstOrDefault(); } preg_auth auth = connect.preg_auth.Where(c => c.user_id == user.id).FirstOrDefault(); if (auth == null) { auth = new preg_auth() { user_id = user.id }; connect.preg_auth.Add(auth); } auth.token = context.OwinContext.Request.Headers["access_token"]; connect.SaveChanges(); var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.social.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.user.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.dev.ToString())); identity.AddClaim(new Claim("id", user.id.ToString())); context.Validated(identity); } else { var client2 = new RestClient("https://www.googleapis.com/oauth2/v1/"); var request2 = new RestRequest("userinfo", Method.GET); request2.AddQueryParameter("alt", "json"); request2.AddQueryParameter("access_token", accessToken); var response2 = client.Execute(request2); if (response2.StatusCode == HttpStatusCode.OK) { var content = JObject.Parse(response2.Content); var userInfo = new GoogleUserInfo() { sub = content["sub"].ToString() }; if (content["name"] != null) { userInfo.name = content["name"].ToString(); } if (content["email"] != null) { userInfo.email = content["email"].ToString(); } if (content["picture"] != null) { userInfo.picture = content["picture"].ToString(); } if (content["given_name"] != null) { userInfo.given_name = content["given_name"].ToString(); } if (content["family_name"] != null) { userInfo.family_name = content["family_name"].ToString(); } PregnancyEntity connect = new PregnancyEntity(); preg_user user = connect.preg_user.Where(c => c.uid == userInfo.sub && c.social_type_id == (int)SysConst.SocialTypes.google).FirstOrDefault(); if (user != null) { //user.email = userInfo.email; //user.first_name = userInfo.name; //user.avatar = userInfo.picture; user.time_last_login = DateTime.Now; connect.SaveChanges(); } else { user = new preg_user(); user.uid = userInfo.sub; user.email = userInfo.email; user.first_name = userInfo.name; user.avatar = userInfo.picture; user.social_type_id = (int)SysConst.SocialTypes.google; user.time_created = DateTime.Now; connect.preg_user.Add(user); SysMethod.createAccountNop(user); connect.SaveChanges(); user = connect.preg_user.Where(c => c.uid == userInfo.sub && c.social_type_id == (int)SysConst.SocialTypes.google).FirstOrDefault(); } preg_auth auth = connect.preg_auth.Where(c => c.user_id == user.id).FirstOrDefault(); if (auth == null) { auth = new preg_auth() { user_id = user.id }; connect.preg_auth.Add(auth); } auth.token = context.OwinContext.Request.Headers["access_token"]; connect.SaveChanges(); var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.social.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.user.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.dev.ToString())); identity.AddClaim(new Claim("id", user.id.ToString())); context.Validated(identity); } else { context.SetError("Invalid grant", SysConst.LOGIN_SOCIAL_FAILED); return; } } } } else if (context.UserName != null && context.Password != null) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); PregnancyEntity connect = new PregnancyEntity(); UserDao dao = new UserDao(); //Check username & password string phone = context.UserName; string password = SysMethod.MD5Hash(context.Password); preg_user user = connect.preg_user.Where(c => c.phone == phone && c.password == password).FirstOrDefault(); if (user != null) { user.time_last_login = DateTime.Now; connect.SaveChanges(); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.dev.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.user.ToString())); identity.AddClaim(new Claim("id", user.id.ToString())); context.Validated(identity); } else if (context.UserName == "WSPadmin" && context.Password == "WSPadmin") { identity.AddClaim(new Claim(ClaimTypes.Role, SysConst.UserType.admin.ToString())); identity.AddClaim(new Claim("id", "0")); context.Validated(identity); } else { context.SetError("Invalid grant", SysConst.LOGIN_FAILED); return; } } }