private void btnLogin_Click(object sender, EventArgs e) { string errorMsg = ""; string email = txtEmail.Text.Trim(); string pwd = txtPwd.Text.Trim(); if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(pwd)) { MessageBox.Show("请输入账号密码!"); return; } var userInfo = new LoginAPI().Login(email, pwd, ref errorMsg); if (userInfo == null) { MessageBox.Show(errorMsg); return; } if (chkPwd.Checked) { new UserService().UpdateAutoLogin(userInfo, email); } else if (chkUser.Checked) { new UserService().UpdateRemeberUserName(userInfo, email); } Main.CurUser.CopyValues(userInfo); this.Close(); }
async void LoginTapped(object sender, EventArgs e) { var fade = (Label)sender; await fade.FadeTo(0, 200); await Task.Delay(100); await fade.FadeTo(1, 200); screenLoading.IsVisible = true; if (Password.Text != "" && Email.Text != "") { if (Email.TextColor != Color.Red) { LoginAPI api = new LoginAPI(Email.Text, Password.Text); api.setCallbacks(this); api.getResponse(); } else { screenLoading.IsVisible = false; DisplayAlert("X", "Please enter a valid email", "OK"); } } else { screenLoading.IsVisible = false; DisplayAlert("X", "Your email or password is blank", "OK"); } //await Navigation.PushModalAsync(new MainPage()); }
public IActionResult LoginAccount(Login account) { var record = LoginAPI.CheckUserExists(account.Email, _clientBaseAddress.BaseURLApi); if (account == null || record == null) { return(RedirectToAction("LoginView", "Login")); } else { var decryptedPassword = EncryptionAPI.DecryptPassword(record.Password, _clientBaseAddress.BaseURLApi); if (account.Password == decryptedPassword) { return(RedirectToAction("Index", "AdAccounts")); } else { return(BadRequest("Invalid Credentials")); } } //var googleUserData = OAuthAPI.GetGoogleUserData(account.AccessToken, _clientBaseAddress.BaseURLApi); //if (account.Email == googleUserData.email) //{ // return RedirectToAction("Index", "AdAccounts"); //} //else //{ // return BadRequest("Invalid Credentials"); //} }
public async Task <IActionResult> Login([FromBody] LoginAPI login) { if (ModelState.IsValid) { var usuario = await _userManager.FindByEmailAsync(login.Email); if (usuario == null) { return(BadRequest(new { Error = "Intento de autenticación inválido" })); } bool correcto = await _userManager.CheckPasswordAsync(usuario, login.Password); if (!correcto) { return(BadRequest(new { Error = "Intento de autenticación inválido" })); } var jwtToken = GenerateJwtToken(usuario); return(Ok(new { Token = jwtToken })); } return(BadRequest()); }
public User(int id, string username, string password, string firstName, string lastName, string email, int membership, LoginAPI loginAPI, int restaurantId = 0, bool restaurantAdmin = false, bool systemAdmin = false, bool deleted = false) : base(id, username, password, firstName, lastName, email, membership, loginAPI, restaurantId, restaurantAdmin, systemAdmin, deleted) { }
public static async Task ClassInitialize(TestContext tc) { UserController.Instance.isTestMode = true; ServerConfig.Instance.serverAddress = "http://csse-s302g3.canterbury.ac.nz:80/testing/api/v1"; loginAPI = new LoginAPI(); drugAPI = new DrugInteractionAPI(); await UnitTestUtils.resetResample(); }
protected void LoginWithtUser(User user) { //LoginWithtUser(user.Username, user.Password); var cookies = LoginAPI.Login(user); Driver.SetCookies(cookies); Driver.Current.Url = "https://www.kika.lt/"; Driver.WriteAllCookies(); }
/* * Function which sends an API call with the inputted username/email and password * to return a user object from the login call. */ private async Task LoginRegisteredUser(string givenUsername, string givenEmail, string givenPassword) { LoginAPI loginAPI = new LoginAPI(); // Attempt login with the newly created account HttpStatusCode loginResult; if (usernameInput.Text != null) { loginResult = await loginAPI.LoginUser(givenUsername, givenPassword); } else { loginResult = await loginAPI.LoginUser(givenEmail, givenPassword); } switch (loginResult) { case HttpStatusCode.OK: // Pop away login screen on successful login await DisplayAlert("", "Account successfully created", "OK"); // Dismiss the register modal dialog await Navigation.PopModalAsync(); // Dismiss the login modal dialog await parentLoginPage.OpenMainPageFromSignUp(); break; case HttpStatusCode.Unauthorized: await DisplayAlert( "Failed to Login", "Incorrent username/password", "OK"); break; case HttpStatusCode.ServiceUnavailable: await DisplayAlert( "Failed to Login", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: await DisplayAlert( "Failed to Login", "Server error", "OK"); break; } }
public override void Initialize(Config config) { endPoint = new HttpEndPoint(config.ApiEndpoint, new EndPointOptions() { Key = config.ApiKey.Value, KeepAlive = false }); api = new LoginAPI(endPoint); }
public IActionResult SaveGoogleAccount(OAuthLogin oauthLogin) { var record = LoginAPI.CheckUserExists(oauthLogin.Email, _clientBaseAddress.BaseURLApi); if (record == null) { var response = OAuthAPI.GenerateToken(_clientBaseAddress.BaseURLApi); oauthLogin.Token = response.access_token; LoginAPI.SaveCredentials(oauthLogin, _clientBaseAddress.BaseURLApi); } return(RedirectToAction("Index", "AdAccounts")); }
/* * Method which is used when a user logs out, opening the login page again. */ private async void LogoutUser() { // Remove token from server LoginAPI loginAPI = new LoginAPI(); await loginAPI.Logout(false); // Logout any currently stored user UserController.Instance.Logout(); // Open the login page var loginPage = new LoginPage(); await Navigation.PopModalAsync(true); }
/* * Method which is used when a user logs out, opening the login page again. */ private async void LogoutClinician() { // Remove token from server LoginAPI loginAPI = new LoginAPI(); await loginAPI.Logout(true); // Clear any previously selected user UserController.Instance.Logout(); // Logout clinician ClinicianController.Instance.Logout(); // Open the login page var loginPage = new LoginPage(); await Navigation.PopModalAsync(true); }
/* * Catches the Google login redirect after successful Google authentication. * Attempts to switch login method for the logged in user to Google */ public async Task Handle_RedirectUriCaught(string code) { string id = await GoogleServices.GetUserId(code); LoginAPI loginApi = new LoginAPI(); HttpStatusCode responseCode = await loginApi.GoogleRegisterUser(UserController.Instance.LoggedInUser.id, id); switch (responseCode) { case HttpStatusCode.OK: await DisplayAlert("", "Login method changed to Google", "OK"); break; case HttpStatusCode.BadRequest: await DisplayAlert("", "Failed to change login method (400)", "OK"); break; case HttpStatusCode.ServiceUnavailable: await DisplayAlert("", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.Unauthorized: await DisplayAlert("", "Unauthorised to modify profile", "OK"); break; case HttpStatusCode.InternalServerError: await DisplayAlert("", "Server error, please try again (500)", "OK"); break; } updateButtons(); }
private void Awake() { if (Instance == null) { Instance = this; loginAPI = new FacebookLoginAPI(); loginAPI.Initialise(this); UserId = null; UserName = null; UserEmail = null; UserLoggedIn = false; } else { Destroy(this); } }
public AbstractUser(int id, string username, string password, string firstName, string lastName, string email, int membership, LoginAPI loginAPI, int restaurantId = 0, bool restaurantAdmin = false, bool systemAdmin = false, bool deleted = false) { this.id = id; this.loginAPI = loginAPI; this.username = username; this.firstName = firstName; this.lastName = lastName; this.password = password; this.email = email; this.membership = membership; this.restaurantId = restaurantId; this.restaurantAdmin = restaurantAdmin; this.systemAdmin = systemAdmin; this.deleted = deleted; }
/// <summary> /// Note: The 'limitblankpassworduse' (Under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa) /// will cause AcceptSecurityContext to return SEC_E_LOGON_DENIED when the correct password is blank. /// </summary> public User Authenticate(string accountNameToAuth, byte[] lmResponse, byte[] ntlmResponse) { if (accountNameToAuth == String.Empty || (String.Equals(accountNameToAuth, "Guest", StringComparison.InvariantCultureIgnoreCase) && IsPasswordEmpty(lmResponse, ntlmResponse) && this.EnableGuestLogin)) { int guestIndex = IndexOf("Guest"); if (guestIndex >= 0) { return(this[guestIndex]); } return(null); } int index = IndexOf(accountNameToAuth); if (index >= 0) { // We should not spam the security event log, and should call the Windows LogonUser API // just to verify the user has a blank password. if (!AreEmptyPasswordsAllowed() && IsPasswordEmpty(lmResponse, ntlmResponse) && LoginAPI.HasEmptyPassword(accountNameToAuth)) { throw new EmptyPasswordNotAllowedException(); } AuthenticateMessage authenticateMessage = new AuthenticateMessage(); authenticateMessage.NegotiateFlags = NegotiateFlags.NegotiateUnicode | NegotiateFlags.NegotiateOEM | NegotiateFlags.RequestTarget | NegotiateFlags.NegotiateSign | NegotiateFlags.NegotiateSeal | NegotiateFlags.NegotiateLanManagerKey | NegotiateFlags.NegotiateNTLMKey | NegotiateFlags.NegotiateAlwaysSign | NegotiateFlags.NegotiateVersion | NegotiateFlags.Negotiate128 | NegotiateFlags.Negotiate56; authenticateMessage.UserName = accountNameToAuth; authenticateMessage.LmChallengeResponse = lmResponse; authenticateMessage.NtChallengeResponse = ntlmResponse; authenticateMessage.Version = Authentication.Version.Server2003; byte[] authenticateMessageBytes = authenticateMessage.GetBytes(); bool success = SSPIHelper.AuthenticateType3Message(m_serverContext, authenticateMessageBytes); if (success) { return(this[index]); } } return(null); }
public async Task <IActionResult> Login([FromBody] LoginAPI Model) { if (Model.Email == null || Model.Password == null) { return(BadRequest()); } IdentityUser User = await UserManager.FindByEmailAsync(Model.Email); if (User is null) { return(BadRequest("Email Not Correct")); } if (await UserManager.CheckPasswordAsync(User, Model.Password)) { return(Ok()); } else { return(BadRequest("Password Not Correct")); } }
private async void LoginClicked(object sender, EventArgs e) { //System.Diagnostics.Debug.WriteLine(user_email.Text + " " + password.Text); try { //System.Diagnostics.Debug.WriteLine(user_email.Text + " " + password.Text); LoginButton.IsEnabled = false; notiLabel.IsVisible = false; var email = user_email.Text; var password = user_password.Text; LoginAPI LA = await App.SvLoginManager.DoLoginAsync(email, password); if (LA.code != "200") { notiLabel.Text = LA.desc; notiLabel.IsVisible = true; } else { var user = new UserProfile(); user.id = "1"; user.email = email; user.sessionid = LA.session; App.sessionId = LA.session; user.fullname = await App.SvLoginManager.GetFullNameWitoutSSAsync(email); await App.UDatabase.SaveItemAsync(user); App.fullname = user.fullname; App.email = email; await PopupNavigation.PopAsync(); } LoginButton.IsEnabled = true; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
public async Task <LoginAPI> PerformLoginAsync(string email, string password) { //Debug.WriteLine(email + " " + password); LoginAPI Items = new LoginAPI(); LoginData logindata = new LoginData() { user_email = email, user_pwd = password }; var uri = new Uri(Constants.RestLoginUrl); Debug.WriteLine("Activate get Login"); try { var json = JsonConvert.SerializeObject(logindata); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = null; Debug.WriteLine("link:" + uri); //var response = await client.GetAsync(uri); response = await client.PostAsync(uri, content); if (response.IsSuccessStatusCode) { var rpcontent = await response.Content.ReadAsStringAsync(); Debug.WriteLine(rpcontent); Items = JsonConvert.DeserializeObject <LoginAPI>(rpcontent); return(Items); } } catch (Exception ex) { Debug.WriteLine(@" ERROR {0}", ex.Message); } throw new NotImplementedException(); }
/// <summary> /// Note: The 'limitblankpassworduse' (Under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa) /// will cause AcceptSecurityContext to return SEC_E_LOGON_DENIED when the correct password is blank. /// </summary> public User Authenticate(byte[] authenticateMessageBytes) { AuthenticateMessage message = new AuthenticateMessage(authenticateMessageBytes); if ((message.NegotiateFlags & NegotiateFlags.NegotiateAnonymous) > 0 || (String.Equals(message.UserName, "Guest", StringComparison.InvariantCultureIgnoreCase) && IsPasswordEmpty(message) && this.EnableGuestLogin)) { int guestIndex = IndexOf("Guest"); if (guestIndex >= 0) { return(this[guestIndex]); } return(null); } int index = IndexOf(message.UserName); if (index >= 0) { // We should not spam the security event log, and should call the Windows LogonUser API // just to verify the user has a blank password. if (!AreEmptyPasswordsAllowed() && IsPasswordEmpty(message) && LoginAPI.HasEmptyPassword(message.UserName)) { throw new EmptyPasswordNotAllowedException(); } bool success = SSPIHelper.AuthenticateType3Message(m_serverContext, authenticateMessageBytes); if (success) { return(this[index]); } } return(null); }
/* * Called when the Sign Up button is clicked */ async void SignUpButtonClicked(Object sender, EventArgs args) { string givenFirstName = InputValidation.Trim(firstNameInput.Text); string givenLastName = InputValidation.Trim(lastNameInput.Text); string givenPassword = InputValidation.Trim(passwordInput.Text); string givenEmail = InputValidation.Trim(emailInput.Text); string givenUsername = InputValidation.Trim(usernameInput.Text); string givenNhi = InputValidation.Trim(nhiInput.Text); if (!ServerConfig.Instance.IsConnectedToInternet()) { await DisplayAlert("", "Server unavailable, please check connection", "OK"); return; } // Check for valid inputs if (!InputValidation.IsValidTextInput(givenFirstName, false, false)) { await DisplayAlert("", "Please enter a valid first name", "OK"); return; } else if (!InputValidation.IsValidTextInput(givenLastName, false, false)) { await DisplayAlert("", "Please enter a valid last name", "OK"); return; } // Check if a username and valid email is entered else if (!InputValidation.IsValidEmail(givenEmail)) { await DisplayAlert("", "Valid email is required", "OK"); return; } else if (!InputValidation.IsValidTextInput(givenUsername, true, false)) { await DisplayAlert("", "Username is required", "OK"); return; } else if (!InputValidation.IsValidNhiInput(givenNhi)) { await DisplayAlert("", "Please enter a valid NHI number", "OK"); return; } else if (!InputValidation.IsValidTextInput(givenPassword, true, false)) { await DisplayAlert("", "Please enter a password", "OK"); return; } // DOB validation is through constraints on the DatePicker in the XAML // Check uniqueness Tuple <bool, bool, bool, bool> uniquenessResult = await isUsernameEmailUnique(); if (!uniquenessResult.Item1 || !uniquenessResult.Item2 || !uniquenessResult.Item3) { // Username + email taken await DisplayAlert( "", "Email/username/NHI is taken", "OK"); return; } LoginAPI loginAPI = new LoginAPI(); User inputUser = new User(); inputUser.name = new List <string> { givenFirstName, "", givenLastName }; inputUser.preferredName = new List <string> { givenFirstName, "", givenLastName }; inputUser.email = givenEmail; inputUser.nhi = givenNhi; inputUser.username = givenUsername; inputUser.password = givenPassword; inputUser.dateOfBirth = new CustomDate(dobInput.Date); inputUser.creationTime = new CustomDateTime(DateTime.Now); //Server requires to initialise the organs and user history items on creation inputUser.organs = new List <Organ>(); inputUser.userHistory = new List <HistoryItem>(); HttpStatusCode registerUserResult = await loginAPI.RegisterUser(inputUser); switch (registerUserResult) { case HttpStatusCode.Created: await LoginRegisteredUser(givenUsername, givenEmail, givenPassword); break; case HttpStatusCode.ServiceUnavailable: await DisplayAlert( "Failed to Register", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: await DisplayAlert( "Failed to Register", "Server error, please try again", "OK"); break; } }
public void Test1() { LoginAPI.Login(User.DefaultKikaUser); }
/* * Brings up lthe Facebook authentication page and either * logs in or creates a new user depending on whether the Facebook ID is recognised */ private async void WebViewOnNavigated(object sender, WebNavigatedEventArgs e) { var accessToken = facebookServices.ExtractAccessTokenFromUrl(e.Url); if (accessToken != "") { FacebookProfile facebookProfile = await facebookServices.GetFacebookProfileAsync(accessToken); string password = "******"; UserAPI userAPI = new UserAPI(); LoginAPI loginAPI = new LoginAPI(); //Do a check to see if user is already in the database - if they are then skip the register and go to login if not just login Tuple <HttpStatusCode, bool> isUniqueEmailResult = await userAPI.isUniqueApiId(facebookProfile.Id); if (isUniqueEmailResult.Item1 != HttpStatusCode.OK) { Console.WriteLine("Failed to connect to server for checking of unique email"); } //This account already exists if (isUniqueEmailResult.Item2 == false) { HttpStatusCode statusCode = await loginAPI.LoginUser(facebookProfile.Id); switch (statusCode) { case HttpStatusCode.OK: // Pop away login screen on successful login HttpStatusCode httpStatusCode = await userAPI.GetUserPhoto(); UserController.Instance.mainPageController.updateMenuPhoto(); await Navigation.PopModalAsync(); await parentLoginPage.OpenMainPageFromSignUp(); break; case HttpStatusCode.Unauthorized: await DisplayAlert( "Failed to Login", "Incorrect username/password", "OK"); break; case HttpStatusCode.ServiceUnavailable: await DisplayAlert( "Failed to Login", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: await DisplayAlert( "Failed to Login", "Server error", "OK"); break; } } else //Create new account { var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); var modalPage = new NavigationPage(new IncompleteFacebookDetailsPage(facebookProfile)); modalPage.Disappearing += (sender2, e2) => { waitHandle.Set(); }; await Navigation.PushModalAsync(modalPage); await Task.Run(() => waitHandle.WaitOne()); facebookProfile.Email = UserController.Instance.FacebookEmail; facebookProfile.Birthday = UserController.Instance.FacebookDateOfBirth; facebookProfile.NHI = UserController.Instance.NHI; User inputUser = new User { name = new List <string> { facebookProfile.FirstName, "", facebookProfile.LastName }, preferredName = new List <string> { facebookProfile.FirstName, "", facebookProfile.LastName }, email = facebookProfile.Email, username = facebookProfile.Email, password = password, dateOfBirth = new CustomDate(DateTime.Parse(facebookProfile.Birthday)), creationTime = new CustomDateTime(DateTime.Now), gender = facebookProfile.Gender.ToUpper(), organs = new List <Organ>(), userHistory = new List <HistoryItem>(), nhi = facebookProfile.NHI }; //Server requires to initialise the organs and user history items on creation HttpStatusCode registerUserResult = await loginAPI.RegisterUser(inputUser); switch (registerUserResult) { case HttpStatusCode.Created: HttpStatusCode registerFacebookUserResult = await loginAPI.FacebookRegisterUser(inputUser.id, facebookProfile.Id); //Set the local profile picture to the picture object HttpClient client = ServerConfig.Instance.client; // Get the single userController instance UserController userController = UserController.Instance; var bytes = await client.GetByteArrayAsync(facebookProfile.Picture.Data.Url); Photo receievedPhoto = new Photo(Convert.ToBase64String(bytes)); userController.photoObject = receievedPhoto; ImageSource source = ImageSource.FromStream(() => new MemoryStream(bytes)); userController.ProfilePhotoSource = source; HttpStatusCode loginUserResult = await loginAPI.LoginUser(facebookProfile.Id); switch (loginUserResult) { case HttpStatusCode.OK: //Upload the photo to the server - must happen after a login as the token is required HttpStatusCode photoUpdated = await userAPI.UpdateUserPhoto(); if (photoUpdated != HttpStatusCode.OK) { Console.WriteLine("Error uploading facebook photo to the server"); } await Navigation.PopModalAsync(); await parentLoginPage.OpenMainPageFromSignUp(); break; case HttpStatusCode.Unauthorized: await DisplayAlert( "Failed to Login", "Incorrect username/password", "OK"); break; case HttpStatusCode.ServiceUnavailable: await DisplayAlert( "Failed to Login", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: await DisplayAlert( "Failed to Login", "Server error", "OK"); break; } break; case HttpStatusCode.ServiceUnavailable: await DisplayAlert( "Failed to Register", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: await DisplayAlert( "Failed to Register", "Username/Email may be taken", "OK"); break; } } } }
public Account() { userCenterAPI = new UserCenterAPI(); loginAPI = new LoginAPI(); guid = Guid.NewGuid().ToString(); }
/* * Called when the Login button is pressed */ async void LoginButtonClicked(object sender, EventArgs args) { IsLoading = true; string givenUsernameEmail = InputValidation.Trim(usernameEmailInput.Text); string givenPassword = InputValidation.Trim(passwordInput.Text); rememberLogin = RememberMeSwitch.IsToggled; if (!InputValidation.IsValidTextInput(givenUsernameEmail, true, false) || !InputValidation.IsValidTextInput(givenPassword, true, false)) { await DisplayAlert("", "Please enter a valid username/email and password", "OK"); IsLoading = false; return; } LoginAPI loginAPI = new LoginAPI(); HttpStatusCode statusCode = await loginAPI.LoginUser(givenUsernameEmail, givenPassword); switch (statusCode) { case HttpStatusCode.OK: // Fetch photo only on user login if (!ClinicianController.Instance.isLoggedIn()) { UserAPI userAPI = new UserAPI(); await userAPI.GetUserPhoto(); } if (ClinicianController.Instance.isLoggedIn()) { baseMainPage.clinicianLoggedIn(); } else { baseMainPage.userLoggedIn(); } if (rememberLogin) { await storeLoginDetails(givenUsernameEmail, givenPassword); } await Navigation.PushModalAsync(baseMainPage); IsLoading = false; usernameEmailInput.Text = ""; passwordInput.Text = ""; break; case HttpStatusCode.Unauthorized: IsLoading = false; await DisplayAlert( "Failed to Login", "Incorrect username/password", "OK"); break; case HttpStatusCode.BadRequest: IsLoading = false; await DisplayAlert( "Failed to Login", "Incorrect username/password", "OK"); break; case HttpStatusCode.ServiceUnavailable: IsLoading = false; await DisplayAlert( "Failed to Login", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: IsLoading = false; await DisplayAlert( "Failed to Login", "Server error", "OK"); break; case HttpStatusCode.Conflict: IsLoading = false; await DisplayAlert( "Failed to Login", "User is deceased. Please consult a Registered Clinician", "OK"); break; } }
/// <summary> /// Logs in as a previously logged in user who did not log out /// </summary> /// <param name="usernameEmail"></param> /// <param name="password"></param> async void LoginStoredUser(string usernameEmail, string password) { IsLoading = true; string givenUsernameEmail = usernameEmail; string givenPassword = password; if (!InputValidation.IsValidTextInput(givenUsernameEmail, true, false) || !InputValidation.IsValidTextInput(givenPassword, true, false)) { await DisplayAlert("", "Username/email and password is invalid", "OK"); return; } LoginAPI loginAPI = new LoginAPI(); HttpStatusCode statusCode = await loginAPI.LoginUser(givenUsernameEmail, givenPassword); switch (statusCode) { case HttpStatusCode.OK: // Fetch photo only on user login if (!ClinicianController.Instance.isLoggedIn()) { UserAPI userAPI = new UserAPI(); await userAPI.GetUserPhoto(); } if (ClinicianController.Instance.isLoggedIn()) { baseMainPage.clinicianLoggedIn(); } else { baseMainPage.userLoggedIn(); } await Navigation.PushModalAsync(baseMainPage); IsLoading = false; usernameEmailInput.Text = ""; passwordInput.Text = ""; break; case HttpStatusCode.Unauthorized: IsLoading = false; await DisplayAlert( "Failed to Login", "Incorrect username/password", "OK"); break; case HttpStatusCode.ServiceUnavailable: IsLoading = false; await DisplayAlert( "Failed to Login", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: IsLoading = false; await DisplayAlert( "Failed to Login", "Server error", "OK"); break; case HttpStatusCode.Conflict: IsLoading = false; await DisplayAlert( "Failed to Login", "User is deceased. Please consult a Registered Clinician", "OK"); break; } }
/* * Attempts to login via Google * If the Google account is not recognised, a new accout is created */ private async Task LoginAsGoogleUser(Tuple <User, string, string> parsedUser) { User googleUser = parsedUser.Item1; string profileImageURL = parsedUser.Item2; string id = parsedUser.Item3; string password = "******"; UserAPI userAPI = new UserAPI(); LoginAPI loginAPI = new LoginAPI(); //Do a check to see if user is already in the database - if they are then skip the register and go to login if not just login Tuple <HttpStatusCode, bool> isUniqueEmailResult = await userAPI.isUniqueApiId(id); if (isUniqueEmailResult.Item1 != HttpStatusCode.OK) { Console.WriteLine("Failed to connect to server for checking of unique email"); } if (isUniqueEmailResult.Item2 == false) { HttpStatusCode statusCode = await loginAPI.LoginUser(id); switch (statusCode) { case HttpStatusCode.OK: // Pop away login screen on successful login HttpStatusCode httpStatusCode = await userAPI.GetUserPhoto(); UserController.Instance.mainPageController.updateMenuPhoto(); baseMainPage.userLoggedIn(); await Navigation.PushModalAsync(baseMainPage); break; case HttpStatusCode.Unauthorized: await DisplayAlert( "Failed to Login", "Incorrect username/password", "OK"); break; case HttpStatusCode.ServiceUnavailable: await DisplayAlert( "Failed to Login", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: await DisplayAlert( "Failed to Login", "Server error", "OK"); break; } } else { await Navigation.PushModalAsync(new GooglePage(this, googleUser, profileImageURL, id)); } IsLoading = false; }
/* * Creates a new user with a Google login */ public async Task RegisterNewUser() { UserAPI userAPI = new UserAPI(); LoginAPI loginAPI = new LoginAPI(); HttpStatusCode registerUserResult = await loginAPI.RegisterUser(googleUser); HttpStatusCode accountUpdate = await loginAPI.GoogleRegisterUser(googleUser.id, api_id); switch (registerUserResult) { case HttpStatusCode.Created: //Set the local profile picture to the picture object HttpClient client = ServerConfig.Instance.client; // Get the single userController instance UserController userController = UserController.Instance; var bytes = await client.GetByteArrayAsync(profileImageURL); Photo receievedPhoto = new Photo(Convert.ToBase64String(bytes)); userController.photoObject = receievedPhoto; ImageSource source = ImageSource.FromStream(() => new MemoryStream(bytes)); userController.ProfilePhotoSource = source; HttpStatusCode loginUserResult = await loginAPI.LoginUser(api_id); switch (loginUserResult) { case HttpStatusCode.OK: //Upload the photo to the server - must happen after a login as the token is required HttpStatusCode photoUpdated = await userAPI.UpdateUserPhoto(); if (photoUpdated != HttpStatusCode.OK) { Console.WriteLine("Error uploading facebook photo to the server"); } await Navigation.PopModalAsync(); await parentLoginPage.OpenMainPageFromSignUp(); break; case HttpStatusCode.Unauthorized: await DisplayAlert( "Failed to Login", "Incorrect username/password", "OK"); break; case HttpStatusCode.ServiceUnavailable: await DisplayAlert( "Failed to Login", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: await DisplayAlert( "Failed to Login", "Server error", "OK"); break; } break; case HttpStatusCode.ServiceUnavailable: await DisplayAlert( "Failed to Register", "Server unavailable, check connection", "OK"); break; case HttpStatusCode.InternalServerError: await DisplayAlert( "Failed to Register", "Username/Email may be taken", "OK"); break; } }