Skip to content

Commit

Permalink
[FIX] Login process issues
Browse files Browse the repository at this point in the history
  • Loading branch information
ilyalehchylin committed Jun 24, 2024
1 parent 82d3be2 commit 7ca563e
Show file tree
Hide file tree
Showing 22 changed files with 155 additions and 244 deletions.
5 changes: 2 additions & 3 deletions source/EduCATS/App.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,13 @@ async Task getProfileInfo()
}

var username = _services.Preferences.UserLogin;
var password = _services.Preferences.UserPassword;

if (string.IsNullOrEmpty(username)) {
return;
}

var profile = await DataAccess.GetProfileInfo(username, password);
AppUserData.SetLoginData(_services, _services.Preferences.UserId, username, password);
var profile = await DataAccess.GetProfileInfo(username);
AppUserData.SetLoginData(_services, _services.Preferences.UserId, username);
AppUserData.SetProfileData(_services, profile);
_services.Preferences.GroupName = profile?.GroupName;
_services.Preferences.Avatar = profile?.Avatar;
Expand Down
15 changes: 10 additions & 5 deletions source/EduCATS/Data/DataAccess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using EduCATS.Data.Models.Calendar;
using EduCATS.Data.Models.User;
using EduCATS.Networking;
using EduCATS.Networking.Models.Login;
using EduCATS.Networking.Models.SaveMarks;
using EduCATS.Networking.Models.SaveMarks.Labs;
using EduCATS.Networking.Models.SaveMarks.LabSchedule;
Expand All @@ -22,7 +23,6 @@ namespace EduCATS.Data
/// </summary>
public static partial class DataAccess
{
public static string Password { get; private set; }
public static string Username { get; private set; }

/// <summary>
Expand All @@ -37,12 +37,18 @@ public async static Task<UserModel> Login(string username, string password)
return await GetDataObject(dataAccess, false) as UserModel;
}

public async static Task<SecondUserModel> LoginTest(string username, string password)
public async static Task<SecondUserModel> GetAccountData()
{
var dataAccess = new DataAccess<SecondUserModel>("login_error", loginCallbackEducatsby(username, password));
var dataAccess = new DataAccess<SecondUserModel>("login_error", getAccountDataCallback());
return await GetDataObject(dataAccess, false) as SecondUserModel;
}

public async static Task<TokenModel> GetToken(string username, string password)
{
var dataAccess = new DataAccess<TokenModel>("login_error", getTokenCallback(username, password));
return await GetDataObject(dataAccess, false) as TokenModel;
}

public async static Task<DeleteAccountModel> DeleteAccount()
{
var dataAccess = new DataAccess<DeleteAccountModel>(
Expand All @@ -56,9 +62,8 @@ public async static Task<DeleteAccountModel> DeleteAccount()
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <returns>User profile data.</returns>
public async static Task<UserProfileModel> GetProfileInfo(string username, string password = "")
public async static Task<UserProfileModel> GetProfileInfo(string username)
{
Password = password;
Username = username;
var dataAccess = new DataAccess<UserProfileModel>(
"login_user_profile_error", getProfileCallback(username), GlobalConsts.DataProfileKey);
Expand Down
6 changes: 4 additions & 2 deletions source/EduCATS/Data/DataAccessCallbacks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ public static partial class DataAccess
static async Task<object> loginCallback(
string username, string password) => await AppServices.Login(username, password);

static async Task<object> loginCallbackEducatsby(
string username, string password) => await AppServices.LoginEducatsBy(username, password);
static async Task<object> getAccountDataCallback() => await AppServices.GetAccountData();

static async Task<object> getTokenCallback(
string username, string password) => await AppServices.GetToken(username, password);

static async Task<object> getLecturesCallbackTest(
int subjectId, int groupId) => await AppServices.GetLecturesEducatsBy(subjectId, groupId);
Expand Down
23 changes: 22 additions & 1 deletion source/EduCATS/Data/DataAccessHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ public partial class DataAccess<T> : IDataAccess<T> where T : new()
/// </summary>
public bool IsConnectionError { get; set; }

/// <summary>
/// Is session expired issue.
/// </summary>
public bool IsSessionExpiredError { get; set; }

/// <summary>
/// Error message localized key.
/// </summary>
Expand Down Expand Up @@ -93,6 +98,13 @@ public async Task<T> GetSingle()
}

var response = await _callback();

if (response.Value == HttpStatusCode.Unauthorized)
{
setError("base_session_expired", sessionExpired: true);
return new T();
}

singleObject = GetAccess(response);

if (singleObject == null) {
Expand All @@ -116,6 +128,13 @@ public async Task<List<T>> GetList()
}

var response = await _callback();

if (response.Value == HttpStatusCode.Unauthorized)
{
setError("base_session_expired", sessionExpired: true);
return new List<T>();
}

list = GetListAccess(response);

if (list == null) {
Expand Down Expand Up @@ -221,12 +240,14 @@ public T GetAccess(KeyValuePair<string, HttpStatusCode> response)
/// Set error details.
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="sessionExpired">Session expired error.</param>
/// <param name="isConnectionError">Is connection error.</param>
void setError(string message, bool isConnectionError = false)
void setError(string message, bool sessionExpired = false, bool isConnectionError = false)
{
IsError = true;
ErrorMessageKey = message;
IsConnectionError = isConnectionError;
IsSessionExpiredError = sessionExpired;
}

/// <summary>
Expand Down
12 changes: 10 additions & 2 deletions source/EduCATS/Data/DataAccessTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ public static partial class DataAccess
/// </summary>
public static bool IsConnectionError { get; set; }

/// <summary>
/// Is session expired issue.
/// </summary>
public static bool IsSessionExpiredError { get; set; }

/// <summary>
/// Error message.
/// </summary>
Expand Down Expand Up @@ -50,7 +55,7 @@ public async static Task<object> GetDataObject<T>(IDataAccess<T> dataAccess, boo
objectToGet = await dataAccess.GetSingle();
}

SetError(dataAccess.ErrorMessageKey, dataAccess.IsConnectionError);
SetError(dataAccess.ErrorMessageKey, dataAccess.IsConnectionError, dataAccess.IsSessionExpiredError);
return objectToGet;
}

Expand Down Expand Up @@ -82,19 +87,22 @@ public static string GetKey(string key, object id)
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="isConnectionError">Is network connection issue.</param>
/// <param name="sessionExpired">Is session expired issue.</param>
/// <remarks>
/// Can be <c>null</c> (if no error occurred).
/// </remarks>
public static void SetError(string message, bool isConnectionError)
public static void SetError(string message, bool isConnectionError, bool sessionExpired)
{
if (message == null) {
IsError = false;
IsConnectionError = false;
IsSessionExpiredError = false;
return;
}

IsError = true;
IsConnectionError = isConnectionError;
IsSessionExpiredError = sessionExpired;
ErrorMessage = CrossLocalization.Translate(message);
}
}
Expand Down
5 changes: 5 additions & 0 deletions source/EduCATS/Data/Interfaces/IDataAccess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ public interface IDataAccess<T>
/// </summary>
bool IsConnectionError { get; set; }

/// <summary>
/// Is error referred to expired session.
/// </summary>
bool IsSessionExpiredError { get; set; }

/// <summary>
/// Error message localization key.
/// </summary>
Expand Down
2 changes: 0 additions & 2 deletions source/EduCATS/Data/Models/User/UserModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,5 @@ public class UserModel

[JsonProperty("UserId")]
public int UserId { get; set; }

public string Password { get; set; }
}
}
3 changes: 1 addition & 2 deletions source/EduCATS/Data/User/AppUserData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,10 @@ public class AppUserData
/// <param name="services">Platfrom services.</param>
/// <param name="userId">User ID.</param>
/// <param name="username">Username.</param>
public static void SetLoginData(IPlatformServices services, int userId, string username, string password)
public static void SetLoginData(IPlatformServices services, int userId, string username)
{
services.Preferences.UserId = userId;
services.Preferences.UserLogin = username;
services.Preferences.UserPassword = password;
UserId = userId;
Username = username;
}
Expand Down
19 changes: 0 additions & 19 deletions source/EduCATS/Helpers/Forms/Settings/AppPrefs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,25 +93,6 @@ public class AppPrefs : IPreferences
/// </summary>
const string _userLoginDefault = null;

/// <summary>
/// Password key.
/// </summary>
const string _userPassKey = "USER_LOGIN";

/// <summary>
/// Default password.
/// </summary>
const string _userPassDefault = null;

/// <summary>
/// Password.
/// </summary>
public string UserPassword
{
get => Preferences.Get(_userPassKey, _userPassDefault);
set => Preferences.Set(_userPassKey, value);
}

/// <summary>
/// Username.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ public interface IPreferences
string Server { get; set; }
bool IsLoggedIn { get; set; }
string UserLogin { get; set; }
string UserPassword { get; set; }
int UserId { get; set; }
int ChosenSubjectId { get; set; }
int GroupId { get; set; }
Expand Down
1 change: 1 addition & 0 deletions source/EduCATS/Localization/be.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"base_connection_error": "Адсутнічае злучэнне з інтэрнэтам. Праверце налады ў сетцы і паспрабуйце зноў",
"base_no_data": "Адсутнічаюць даныя для адлюстравання",
"base_something_went_wrong": "Нешта пайшло не так. Паўтарыце спробу або звярніцеся ў службу падтрымкі.",
"base_session_expired": "Сесія скончылася. Калі ласка, увайдзіце ў рахунак зноў.",

"contributor_ilya_lehchylin": "Ілля Легчылін",
"contributor_julia_popova": "Юлія Папова",
Expand Down
1 change: 1 addition & 0 deletions source/EduCATS/Localization/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"base_connection_error": "Keine Internetverbindung. Überprüfen Sie die Netzwerkeinstellungen und versuchen Sie es erneut.",
"base_no_data": "Keine Daten angezeigt werden",
"base_something_went_wrong": "Etwas ist schief gelaufen. Bitte versuchen Sie es erneut oder wenden Sie sich an den Support.",
"base_session_expired": "Die Sitzung ist abgelaufen. Bitte melden Sie sich erneut bei Ihrem Konto an.",

"contributor_ilya_lehchylin": "Ilya Legtschilin",
"contributor_julia_popova": "Yuliya Popova",
Expand Down
1 change: 1 addition & 0 deletions source/EduCATS/Localization/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"base_connection_error": "No internet connection. Check your network settings and try again.",
"base_no_data": "No data to display",
"base_something_went_wrong": "Something went wrong. Please try again or contact support.",
"base_session_expired": "Session has been expired. Please log into account again.",

"contributor_ilya_lehchylin": "Ilya Lehchylin",
"contributor_julia_popova": "Julia Popova",
Expand Down
1 change: 1 addition & 0 deletions source/EduCATS/Localization/lt.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"base_connection_error": "Nėra interneto ryšio. Patikrinkite tinklo nustatymus ir bandykite dar kartą.",
"base_no_data": "Nėra rodomų duomenų",
"base_something_went_wrong": "Kažkas nutiko. Bandykite dar kartą arba susisiekite su palaikymo komanda.",
"base_session_expired": "Sesija ir beigusies. Lūdzu, vēlreiz piesakieties savā kontā.",

"contributor_ilya_lehchylin": "Ilya Lehchylin",
"contributor_julia_popova": "Julia Popova",
Expand Down
1 change: 1 addition & 0 deletions source/EduCATS/Localization/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"base_connection_error": "Brak połączenia z Internetem. Sprawdź ustawienia sieci i spróbuj ponownie.",
"base_no_data": "Brak danych do wyświetlenia",
"base_something_went_wrong": "Coś poszło nie tak. Spróbuj ponownie lub skontaktuj się z pomocą techniczną.",
"base_session_expired": "Sesja wygasła. Proszę zalogować się ponownie na swoje konto.",

"contributor_ilya_lehchylin": "Ilja Legczilin",
"contributor_julia_popova": "Julia Popowa",
Expand Down
3 changes: 1 addition & 2 deletions source/EduCATS/Localization/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"base_connection_error": "Нет соединения с интернетом. Проверьте настройки сети и попробуйте снова.",
"base_no_data": "Нет данных для отображения",
"base_something_went_wrong": "Что-то пошло не так. Повторите попытку или обратитесь в службу поддержки.",
"base_session_expired": "Сессия истекла. Пожалуйста, войдите в аккаунт снова.",

"contributor_ilya_lehchylin": "Илья Легчилин",
"contributor_julia_popova": "Юлия Попова",
Expand Down Expand Up @@ -60,7 +61,6 @@
"today_calendar_error": "Произошла ошибка во время получения списка предметов в календаре. Пожалуйста, обновите страницу или обратитесь в службу поддержки.",
"today_account_error": "Произошла ошибка во время получения информацию об аккаунте. Пожалуйста, обновите страницу или обратитесь в службу поддержки.",


"news_details_title": "Новости",

"subjects_choose": "Выберите предмет",
Expand Down Expand Up @@ -246,4 +246,3 @@
"demo_files_download_error": "Загрузка обучающих материалов недоступна для демонстрационного аккаунта.",
"demo_delete_account_error": "Удаление демонстрационного аккаунта невозможно."
}

16 changes: 14 additions & 2 deletions source/EduCATS/Networking/AppServices/AppServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,21 @@ public static async Task<object> Login(string username, string password)
return await AppServicesController.Request(Links.Login, body);
}

public static async Task<object> LoginEducatsBy(string username, string password)
public static async Task<object> GetAccountData()
{
return await AppServicesController.Request(Links.LoginTest);
return await AppServicesController.Request(Links.GetAccountData);
}

public static async Task<object> GetToken(string username, string password)
{
var credentials = new TokenCredentials
{
Username = username,
Password = password
};

var body = JsonController.ConvertObjectToJson(credentials);
return await AppServicesController.Request(Links.GetToken, body);
}

/// <summary>
Expand Down
12 changes: 10 additions & 2 deletions source/EduCATS/Networking/Links.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,20 @@
public static class Links
{
/// <summary>
/// Authorize URL.
/// Account information URL.
/// </summary>
public static string LoginTest => $"{Servers.Current}/Account/UserSessionCheck";
public static string GetAccountData => $"{Servers.Current}/Account/UserSessionCheck";

/// <summary>
/// Authorize URL (for deprecated URLs).
/// </summary>
public static string Login => $"{Servers.Current}/RemoteApi/Login";

/// <summary>
/// Access token retrieval URL.
/// </summary>
public static string GetToken => $"{Servers.Current}/Account/LoginJWT";

/// <summary>
/// Authorize URL.
/// </summary>
Expand Down
23 changes: 23 additions & 0 deletions source/EduCATS/Networking/Models/Login/TokenCredentials.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Newtonsoft.Json;

namespace EduCATS.Networking.Models.Login
{
/// <summary>
/// Token <c>POST</c> model.
/// </summary>
public class TokenCredentials
{
/// <summary>
/// User login.
/// </summary>
[JsonProperty("userName")]
public string Username { get; set; }

/// <summary>
/// Password.
/// </summary>
[JsonProperty("password")]
public string Password { get; set; }
}
}

Loading

0 comments on commit 7ca563e

Please sign in to comment.