public async Task <DinazorResult <TokenUser> > Login(BaseTokenUser user) { var result = new DinazorResult <TokenUser>(); using (var ctx = new DinazorContext()) { //TODO Hash(password) var exists = await ctx.User.AnyAsync(l => !l.IsDeleted && l.Username == user.Username && l.Password == user.Password); if (exists) { // get more detail later var userEntity = ctx.User.FirstOrDefault( l => !l.IsDeleted && l.Username == user.Username && l.Password == user.Password); result.Data = ToTokenUser(userEntity); result.Success(); } else { //log result.Status = ResultStatus.LoginFailed; return(result); } return(result); } }
public DinazorResult <ConfigurationDto> GetAllConfiguration() { var result = new DinazorResult <ConfigurationDto>(); result.Data = new ConfigurationDto(); using (var ctx = new DinazorContext()) { var dataSet = ctx.Configurations.ToList(); foreach (var item in dataSet) { if (result.Data.ConfigurationMap.ContainsKey(item.Key)) { (result.Data.ConfigurationMap[item.Key]).Add(item.Value); } else { result.Data.ConfigurationMap[item.Key] = new List <string>(); (result.Data.ConfigurationMap[item.Key]).Add(item.Value); } } result.Success(); } return(result); }
public DinazorResult <bool> IsUserAlreadyLoggedIn(string username, string password) { var result = new DinazorResult <bool>(); result.Data = false; if (_tokenUsers.IsEmpty) { result.Data = false; result.Success(); return(result); } foreach (var item in _tokenUsers) { if (item.Value.Username == username && item.Value.Password == password) { result.Data = true; result.Success(); return(result); } else { result.Data = false; result.Success(); } } return(result); }
public async Task <DinazorResult <List <OrganizationLicenceDto> > > IsLicenceValid(ClientDto clientDto) { var result = new DinazorResult <List <OrganizationLicenceDto> >(); // try to the generate the client identifier according to the given information var clientIdentifier = clientDto.BiosVersion + clientDto.HddSerialNo + clientDto.Username + clientDto.Password; if (clientIdentifier != clientDto.ClientIdentifier) { result.Status = ResultStatus.Unauthorized; return(result); } //then check the database if there is a row with given information var clientIdResult = await _licenceOperation.GetClientByClientIdentifier(clientIdentifier); if (!clientIdResult.IsSuccess) { //something went wrong return(result); } clientDto.Id = clientIdResult.Data; // then get the client active licences var activeLicencesResult = await _licenceOperation.GetActiveLicence(clientDto.Id); return(activeLicencesResult); }
public async Task <DinazorResult <List <OrganizationLicenceDto> > > Post(ClientDto clientDto) { /*clientDto.BiosVersion = "1.1.1"; * clientDto.ClientIdentifier = "1.1.11uinan123"; * clientDto.HddSerialNo = "1"; * clientDto.Password = "******"; * clientDto.Username = "******";*/ using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(BaseUrl); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // var clientDtoJson = JsonConvert.SerializeObject(clientDto); //var content = new StringContent(clientDtoJson, Encoding.UTF8, "application/json"); HttpContent content = new FormUrlEncodedContent(GetContent(clientDto)); HttpResponseMessage responseMessage = await client.PostAsync("api/Licence", content).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode()); var res = await responseMessage.Content.ReadAsStringAsync(); DinazorResult <List <OrganizationLicenceDto> > result = new DinazorResult <List <OrganizationLicenceDto> >(); result = JsonConvert.DeserializeObject <DinazorResult <List <OrganizationLicenceDto> > >(res); // result.Data= JsonConvert.DeserializeObject<List<OrganizationLicenceDto>>(res); //result.Success(); return(result); } }
public async Task <DinazorResult> AssignRoleGroupToUserGroup(long idRoleGroup, long idUserGroup) { var result = new DinazorResult(); //check role group id var exists = _roleGroupOperation.Exists(idRoleGroup); if (!exists.IsSuccess) { return(result); } if (!exists.Data) { result.Status = ResultStatus.NoSuchObject; return(result); } //check user group id exists = _userGroupOperation.Exists(idUserGroup); if (!exists.IsSuccess) { return(result); } if (!exists.Data) { result.Status = ResultStatus.NoSuchObject; return(result); } //so far so good using (var ctx = new DinazorContext()) { //already added var data = await ctx.Authorization.FirstOrDefaultAsync(l => l.IdUserGroup == idUserGroup && l.IdRoleGroup == idRoleGroup); if (data != null) { result.Status = ResultStatus.AlreadyAdded; return(result); } Authorization authorization = new Authorization(); authorization.IdUserGroup = idUserGroup; authorization.IdRoleGroup = idRoleGroup; ctx.Authorization.Add(authorization); try { await ctx.SaveChangesAsync(); result.Success(); } catch (Exception e) { result.Status = ResultStatus.UnknownError; } } return(result); }
public async Task <DinazorResult> Delete(long id) { if (id == DinazorConstant.SuperUserId) { var result = new DinazorResult(); result.Status = ResultStatus.Unauthorized; return(result); } return(await _userOperation.Delete(id)); }
public async Task <DinazorResult> Update(UserDto dto) { if (dto.Id == DinazorConstant.SuperUserId) { var result = new DinazorResult(); result.Status = ResultStatus.Unauthorized; return(result); } return(await _userOperation.Update(dto)); }
public async Task <DinazorResult> AssignRoleToRoleGroup(long idRole, long idRoleGroup) { var result = new DinazorResult(); // check role id var exists = _roleOperation.Exists(idRole); if (!exists.IsSuccess) { return(result); } if (!exists.Data) { result.Status = ResultStatus.NoSuchObject; return(result); } //check role group id exists = _roleGroupOperation.Exists(idRoleGroup); if (!exists.IsSuccess) { return(result); } if (!exists.Data) { result.Status = ResultStatus.NoSuchObject; return(result); } //so far so good using (var ctx = new DinazorContext()) { //already added var alreadyAdded = ctx.RelRoleRoleGroup.Any(l => l.IdRole == idRole && l.IdRoleGroup == idRoleGroup); if (alreadyAdded) { result.Status = ResultStatus.AlreadyAdded; return(result); } RelRoleRoleGroup roleRoleGroup = new RelRoleRoleGroup(); roleRoleGroup.IdRole = idRole; roleRoleGroup.IdRoleGroup = idRoleGroup; var willBeAdded = ctx.RelRoleRoleGroup.Add(roleRoleGroup); try { await ctx.SaveChangesAsync(); result.Success(); //result.ObjectId = willBeAdded; } catch (Exception e) { result.Status = ResultStatus.UnknownError; } } return(result); }
public async Task <DinazorResult> AssignUserToUserGroup(long idUser, long idUserGroup) { var result = new DinazorResult(); // check user id var exists = _userOperation.Exists(idUser); if (!exists.IsSuccess) { return(result); } if (!exists.Data) { result.Status = ResultStatus.NoSuchObject; return(result); } //check user group id exists = _userGroupOperation.Exists(idUserGroup); if (!exists.IsSuccess) { return(result); } if (!exists.Data) { result.Status = ResultStatus.NoSuchObject; return(result); } //so far so good using (var ctx = new DinazorContext()) { //already added var alreadyAdded = ctx.RelUserUserGroup.Any(l => l.IdUser == idUser && l.IdUserGroup == idUserGroup); if (alreadyAdded) { result.Status = ResultStatus.AlreadyAdded; return(result); } RelUserUserGroup userUserGroup = new RelUserUserGroup(); userUserGroup.IdUser = idUser; userUserGroup.IdUserGroup = idUserGroup; var willBeAdded = ctx.RelUserUserGroup.Add(userUserGroup); try { await ctx.SaveChangesAsync(); result.Success(); //result.ObjectId = willBeAdded; } catch (Exception e) { result.Status = ResultStatus.UnknownError; } } return(result); }
public async Task <DinazorResult <List <TownDto> > > GetTownsByCityId(long idCity) { var result = new DinazorResult <List <TownDto> >(); using (var ctx = new DinazorContext()) { result.Data = ctx.Town.Where(l => l.City.Id == idCity).Select(new TownDto().Select()).ToList(); result.Success(); } return(result); }
public DinazorResult <TokenUser> GetUserByToken(string token) { var result = new DinazorResult <TokenUser>(); if (!string.IsNullOrEmpty(token) && IsTokenExists(token).IsSuccess) { result.Data = _tokenUsers[token]; result.Data.IsAuthenticated = true; result.Success(); } return(result); }
public async Task <DinazorResult> DetachRoleFromRoleGroup(long idRole, long idRoleGroup) { var result = new DinazorResult(); // check role id var exists = _roleOperation.Exists(idRole); if (!exists.IsSuccess) { return(result); } if (!exists.Data) { result.Status = ResultStatus.NoSuchObject; return(result); } //check role group id exists = _roleGroupOperation.Exists(idRoleGroup); if (!exists.IsSuccess) { return(result); } if (!exists.Data) { result.Status = ResultStatus.NoSuchObject; return(result); } //so far so good using (var ctx = new DinazorContext()) { //already added var data = await ctx.RelRoleRoleGroup.FirstOrDefaultAsync(l => l.IdRole == idRole && l.IdRoleGroup == idRoleGroup); if (data == null) { result.Status = ResultStatus.NoSuchObject; return(result); } ctx.RelRoleRoleGroup.Remove(data); try { await ctx.SaveChangesAsync(); result.Success(); } catch (Exception e) { result.Status = ResultStatus.UnknownError; } } return(result); }
public async Task <DinazorResult <List <RoleDto> > > GetRoleByIdRoleGroup(long idRoleGroup) { var result = new DinazorResult <List <RoleDto> >(); using (var ctx = new DinazorContext()) { var select = new RoleDto().Select().Expand(); result.Data = ctx.RelRoleRoleGroup.Where(l => l.IdRoleGroup == idRoleGroup) .Select(l => l.Role).Select(select).ToList(); result.Success(); } return(result); }
public static void RedirectWithData(DinazorResult result) { var data = result != null?JsonConvert.SerializeObject(result) : string.Empty; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; HttpContext.Current.Response.ContentType = "application/json"; HttpContext.Current.Response.AddHeader("content-length", data.Length.ToString()); HttpContext.Current.Response.Write(data); HttpContext.Current.Response.End(); }
public async Task <DinazorResult <List <UserDto> > > GetUserByIdUserGroup(long idUserGroup) { var result = new DinazorResult <List <UserDto> >(); using (var ctx = new DinazorContext()) { var select = new UserDto().Select().Expand(); result.Data = ctx.RelUserUserGroup.Where(l => l.IdUserGroup == idUserGroup && !l.User.IsDeleted) .Select(l => l.User).Select(select).ToList(); result.Success(); } return(result); }
public DinazorResult <TokenUser> GetUserByUsername(string username) { var result = new DinazorResult <TokenUser>(); foreach (var item in _tokenUsers) { if (item.Value.Username == username) { result.Data = item.Value; result.Success(); return(result); } } return(result); }
public DinazorResult IsTokenExists(string token) { var result = new DinazorResult(); if (string.IsNullOrEmpty(token)) { result.Status = ResultStatus.MissingRequiredParamater; return(result); } if (_tokenUsers.ContainsKey(token)) { result.Status = ResultStatus.Success; return(result); } return(result); }
public async Task <DinazorResult <List <long> > > GetUserByIdWithRoles(long idUser) { var result = new DinazorResult <List <long> >(); using (var ctx = new DinazorContext()) { var queryResult = from ruug in ctx.RelUserUserGroup join auth in ctx.Authorization on ruug.IdUserGroup equals auth.IdUserGroup join rrrg in ctx.RelRoleRoleGroup on auth.IdRoleGroup equals rrrg.IdRoleGroup join r in ctx.Role on rrrg.IdRole equals r.Id select r.Id; result.Success(); result.Data = await queryResult.ToListAsync(); } return(result); }
//TODO log public void OnException(ExceptionContext context) { if (context.Exception.GetType() == typeof(DinazorAuthorizationException)) { var result = new DinazorResult(); result.Message = context.Exception.Message; result.Status = ResultStatus.Unauthorized; /* context.Result = new ObjectResult(result) * { * StatusCode = 400, * DeclaredType = typeof(DinazorResult) * };*/ } _log.Error("Exception occured ", context.Exception); }
public async Task <DinazorResult <long> > GetClientByClientIdentifier(string clientIdentifier) { var result = new DinazorResult <long>(); using (var ctx = new DinazorContext()) { var model = ctx.Client.FirstOrDefault(l => !l.IsDeleted && l.ClientIdentifier == clientIdentifier); if (model != null && model.Id > 0) { result.Data = model.Id; result.Success(); return(result); } } result.Data = -1; return(result); }
public DinazorResult CheckRequiredField(MethodInfo methodInfo, IMethodCallMessage msg) { DinazorResult result = new DinazorResult { Status = ResultStatus.Success }; //try to find required attributes var requiredParameters = methodInfo.GetParameters() .Where( l => l.GetCustomAttributes(false).FirstOrDefault(m => m is RequiredAttribute) != null).ToList(); foreach (var parameterMessage in requiredParameters) { var parameter = msg.GetInArg(parameterMessage.Position); if (parameter == null) { result.Message = parameterMessage.Name; return(result); } if (parameter.GetType().IsPrimitive) { continue; } Type type = parameter.GetType(); var requiredSubParameters = type.GetProperties().Where(l => l.GetCustomAttributes(false).FirstOrDefault(z => z.GetType() == typeof(RequiredAttribute)) != null).ToList(); foreach (var propertyInfo in requiredSubParameters) { var value = propertyInfo.GetValue(parameter); if (value == null || value.ToString() == "") { string columnName = propertyInfo.Name; string errorMessage = propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), false).Cast <RequiredAttribute>().Single().ErrorMessage; result.Message = LocaleManager.GetMessage(errorMessage, new string[1] { columnName }); result.Status = ResultStatus.MissingRequiredParamater; _log.Error("Missing Required Parameter : " + columnName); return(result); } } } return(result); }
public async Task <DinazorResult <Guid> > GetAuthorizationIdByUserGroupId(long idUserGroup) { var result = new DinazorResult <Guid>(); using (var ctx = new DinazorContext()) { var userGroup = await ctx.UserGroup.FirstOrDefaultAsync(l => l.Id == idUserGroup); if (userGroup == null) { result.Status = ResultStatus.NoSuchObject; return(result); } //result.Data = userGroup.AuthorizationId; result.Success(); } return(result); }
public async Task <DinazorResult <List <OrganizationLicenceDto> > > GetActiveLicence(long clientId) { var result = new DinazorResult <List <OrganizationLicenceDto> >(); using (var ctx = new DinazorContext()) { result.Data = ctx.OrganizationLicence .Include(l => l.Client) .Include(l => l.LicenceKey) .Include(l => l.ModuleEnum) .Include(l => l.Organization) .Where(l => l.IdClient == clientId && l.ExpiresAt >= DateTime.Now && l.IsInUse) .Select(new OrganizationLicenceDto().Select()) .ToList(); result.Success(); } return(result); }
public IMessage SyncProcessMessage(IMessage msg) { var watch = System.Diagnostics.Stopwatch.StartNew(); var mcm = (IMethodCallMessage)msg; var method = ((MethodInfo)mcm.MethodBase); var methodName = method.Name; var className = string.Empty; if (method.DeclaringType != null) { className = method.DeclaringType.Name; } Log.DebugFormat("[{0}] Execution for {1}", className, methodName); var result = PreProcess(ref mcm); if (!result.IsSuccess) { Type returnType = method.ReturnType; var genericReturnType = returnType.GenericTypeArguments[0]; DinazorResult instance = (DinazorResult)Activator.CreateInstance(genericReturnType); instance.Message = result.Message; instance.Status = result.Status; var task = Task.Factory.StartNew(() => instance); var task2 = Convert.ChangeType(task, returnType); return(new ReturnMessage(task2, null, 0, null, mcm)); } var rtnMsg = NextSink.SyncProcessMessage(msg); var mrm = (rtnMsg as IMethodReturnMessage); PostProcess((IMethodCallMessage)msg, ref mrm); watch.Stop(); Log.DebugFormat("[{0}] Executed Method for {1} time : {2} ms", className, methodName, watch.ElapsedMilliseconds); return(mrm); }
public DinazorResult <TokenUser> GetUserByToken(string token) { var result = new DinazorResult <TokenUser>(); if (!string.IsNullOrEmpty(token)) { if (token == DinazorConstant.DinazorInternalCommunicationToken) { result.Data = new TokenUser(); result.Data.Token = "dinazor"; result.Data.Id = 1; result.Data.Username = "******"; result.Data.Password = "******"; result.Data.IsAuthenticated = true; result.Success(); return(result); } result = _tokenStorer.GetUserByToken(token); } return(result); }
public DinazorResult IsAuthorized(string token, long role) { var result = new DinazorResult(); if (token == DinazorConstant.DinazorInternalCommunicationToken) { result.Success(); return(result); } var userResult = GetUserByToken(token); if (userResult.IsSuccess) { if (userResult.Data != null) { var roleList = userResult.Data.RoleList; foreach (var item in roleList) { if (item == role) { result.Success(); return(result); } } result.Status = ResultStatus.Unauthorized; } else { result.Status = ResultStatus.SessionNotValid; } } else { result.Status = userResult.Status; return(result); } return(result); }
public DinazorResult IsValid() { var result = new DinazorResult(); var properties = GetType().GetProperties(); foreach (var propertyInfo in properties) { if (propertyInfo.Name == "IsExist" || propertyInfo.Name == "Select") { continue; } var attrs = propertyInfo.GetCustomAttributes(true); var value = propertyInfo.GetValue(this); var validAttr = attrs.OfType <ValidationAttribute>().FirstOrDefault(valid => !valid.IsValid(value)); if (validAttr == null) { continue; } result.Message = string.IsNullOrEmpty(validAttr.ErrorMessageResourceName) ? (string.IsNullOrEmpty(validAttr.ErrorMessage) ? validAttr.FormatErrorMessage(propertyInfo.Name) : validAttr.ErrorMessage) : validAttr.ErrorMessageResourceName; result.Status = ResultStatus.InValidParamater; return(result); } return(result.Success()); }
public async Task <DinazorResult <TokenUser> > Login(BaseTokenUser user) { if (user == null) { var res = new DinazorResult <TokenUser>(); res.Status = ResultStatus.NoSuchObject; return(res); } //firstly check the user whether alredy logged in or not var alreadyLoggedInResult = IsUserAlreadyLoggedIn(user.Username, user.Password); if (!alreadyLoggedInResult.IsSuccess) { return(new DinazorResult <TokenUser>()); } if (alreadyLoggedInResult.Data) { _log.Info("user is already logged in"); //user already logged in. get the user return(GetUserByUsername(user.Username)); } // LICENCE CONTROL /* bool anyCommunicationProblem = false; * DinazorRestClient dinazorRestClient = new DinazorRestClient(); * DinazorResult<List<OrganizationLicenceDto>> licenceResult = new DinazorResult<List<OrganizationLicenceDto>>(); * try * { * licenceResult = await dinazorRestClient.Post(user.Client); * } * catch (Exception e) * { * _log.Error("licence manager communication problem",e); * anyCommunicationProblem = true; * licenceResult.Success(); * } * * if (!licenceResult.IsSuccess) * { * var licenceErrorResult = new DinazorResult<TokenUser> { Status = licenceResult.Status }; * return licenceErrorResult; * } * * //validate the licence * if (!anyCommunicationProblem && licenceResult.Data.Count <= 0) * { * var noLicenceResult = new DinazorResult<TokenUser> { Status = ResultStatus.NoLicence }; * return noLicenceResult; * }*/ if (true) { // try to login var result = await _authorizationOperation.Login(user); if (result.IsSuccess) { //generate the token var token = TokenGenerator.GenerateUniqueId(); //control the token if it already exists while (_tokenStorer.IsTokenExists(token).Status == ResultStatus.Success) { token = TokenGenerator.GenerateUniqueId(); } var tokenUser = result.Data; tokenUser.Token = token; //set the licence information tokenUser.Client = user.Client; tokenUser.IsLicenceValidated = true; // tokenUser.OrganizationLicence = licenceResult.Data; // get the roles according to licenced modules var userManager = IocManager.Instance.Resolve <IUserManager>(); var roleListResult = await userManager.GetUserByIdWithRoles(tokenUser.Id); if (roleListResult.IsSuccess) { tokenUser.RoleList = roleListResult.Data; } else { _log.Error("error while getting the role list"); } //store the user _tokenStorer.StoreTheToken(token, tokenUser); DinazorPrincipal.AuthenticateUser(token); LoginSubscriber.Broadcast(tokenUser); result.Data = tokenUser; return(result); } return(result); } /* else if (anyCommunicationProblem) * { * * }*/ return(null); }
private DinazorResult PreProcess(ref IMethodCallMessage msg) { Type type = Type.GetType(_obj.GetType().FullName); foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) { type = asm.GetType(_obj.GetType().FullName); if (type != null) { break; } } ParameterInfo[] paramInfoArr = msg.MethodBase.GetParameters(); Type[] typeArr = new Type[paramInfoArr.Length]; int ii = 0; foreach (var item in paramInfoArr) { typeArr[ii] = item.ParameterType; ii++; } MethodInfo methodInfo = null; if (type != null) { methodInfo = type.GetMethod(msg.MethodName, typeArr); } var result = new DinazorResult().Success(); // Authorization if (methodInfo == null) { result.Status = ResultStatus.UnknownError; return(result); } var authorizations = (AuthorizationAttribute[])methodInfo.GetCustomAttributes(typeof(AuthorizationAttribute), true); if (authorizations.Select(t => t.IsAuthorizated()).Any(isSuccess => !isSuccess)) { throw new DinazorAuthorizationException(new DinazorResult() { Status = ResultStatus.Unauthorized, Message = "unauthorized" }); } //required DinazorRequiredAttribute[] required = (DinazorRequiredAttribute[])methodInfo.GetCustomAttributes(typeof(DinazorRequiredAttribute), true); for (int i = 0; i < required.Length; i++) { result = required[i].CheckRequiredField(methodInfo, msg); if (!result.IsSuccess) { return(result); } } //info logger var info = (InfoLoggerAttribute[])methodInfo.GetCustomAttributes(typeof(InfoLoggerAttribute), true); foreach (var t in info) { t.Log(methodInfo, msg); } //Pre Process /* var attrs = (PreProcessAttribute[])msg.MethodBase.GetCustomAttributes(typeof(PreProcessAttribute), true); * foreach (var t in attrs) * { * result = t.Processor.Process(ref msg); * if (!result.IsSuccess) * { * return result; * } * }*/ return(result); }