Example #1
0
        public void GenerateEnvironment()
        {
            var authRules = XDocument.Load(@"D:\Signum\Southwind\Southwind.Load\AuthRules.xml"); //Change this route if necessary. Only god knows where MSTest is running.

            SouthwindEnvironment.Start();

            Administrator.TotalGeneration();

            Schema.Current.Initialize();

            OperationLogic.AllowSaveGlobally = true;

            using (AuthLogic.Disable())
            {
                SouthwindEnvironment.LoadBasics();

                AuthLogic.LoadRoles(authRules);
                SouthwindEnvironment.LoadEmployees();
                SouthwindEnvironment.LoadUsers();
                SouthwindEnvironment.LoadProducts();
                SouthwindEnvironment.LoadCustomers();
                SouthwindEnvironment.LoadShippers();

                AuthLogic.ImportRulesScript(authRules, interactive: false).PlainSqlCommand().ExecuteLeaves();
            }

            OperationLogic.AllowSaveGlobally = false;
        }
Example #2
0
        public static bool LoginFromCookie(ActionContext ac)
        {
            using (AuthLogic.Disable())
            {
                try
                {
                    if (!ac.HttpContext.Request.Cookies.TryGetValue(CookieName, out string ticketText) || !ticketText.HasText())
                    {
                        return(false);   //there is no cookie
                    }
                    var httpConnection = ac.HttpContext.Features.Get <IHttpConnectionFeature>();

                    UserEntity user = UserTicketLogic.UpdateTicket(httpConnection.RemoteIpAddress.ToString(), ref ticketText);

                    AuthServer.OnUserPreLogin(ac, user);

                    ac.HttpContext.Response.Cookies.Append(CookieName, ticketText, new CookieOptions
                    {
                        Domain  = ac.HttpContext.Request.Host.Host.ToString(),
                        Path    = new UrlHelper(ac).Content("~/"),
                        Expires = DateTime.UtcNow.Add(UserTicketLogic.ExpirationInterval),
                    });

                    AuthServer.AddUserSession(ac, user);
                    return(true);
                }
                catch
                {
                    //Remove cookie
                    RemoveCookie(ac);

                    return(false);
                }
            }
        }
Example #3
0
        public static void RegisterRoleTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition)
        {
            sb.Schema.Settings.AssertImplementedBy((UserChartEntity uq) => uq.Owner, typeof(RoleEntity));

            TypeConditionLogic.RegisterCompile <UserChartEntity>(typeCondition,
                                                                 uq => AuthLogic.CurrentRoles().Contains(uq.Owner) || uq.Owner == null);
        }
Example #4
0
        public UserEntity ChangePassword(ChangePasswordRequest request)
        {
            if (string.IsNullOrEmpty(request.oldPassword))
            {
                throw ModelException("oldPassword", AuthMessage.PasswordMustHaveAValue.NiceToString());
            }

            if (string.IsNullOrEmpty(request.newPassword))
            {
                throw ModelException("newPassword", AuthMessage.PasswordMustHaveAValue.NiceToString());
            }

            var user = UserEntity.Current;

            if (!user.PasswordHash.SequenceEqual(Security.EncodePassword(request.oldPassword)))
            {
                throw ModelException("oldPassword", AuthMessage.InvalidPassword.NiceToString());
            }

            user.PasswordHash = Security.EncodePassword(request.newPassword);
            using (AuthLogic.Disable())
                user.Execute(UserOperation.Save);

            return(user);
        }
Example #5
0
        private void AddFriendListEntryHandler(List <object> objects)
        {
            bool success = AuthLogic.AddFriend((FriendList.Type)(uint) objects[2], (string)objects[3], (string)objects[4]);

            Network.AuthServer.TransactionCounter = (uint)objects[1];
            Network.AuthServer.SendTransactionSuccessCode(success ? TransactionSuccessCode.Success : TransactionSuccessCode.Aborted);
        }
Example #6
0
        // GET: Course/Details/5
        public ActionResult Details(string token, string id)
        {
            string username = AuthLogic.CheckToken(token);

            if (username == "")
            {
                throw new Exception("NotAuthorized");
            }
            ViewData["token"] = token;
            var course = Course.GetCourse(id);

            // cast to Subscribed
            CourseView courseView = CourseView.CastFromCourseModel(course.ModelCourse);

            if (courseView.Author == username)
            {
                ViewData["isAuthor"] = true;
            }
            else
            {
                ViewData["isAuthor"] = false;
            }
            ViewData["courseId"] = id;

            // return the subscribed one!
            return(View(courseView));
        }
Example #7
0
        internal void SetRules(BaseRulePack <TypeAllowedRule> rules)
        {
            using (AuthLogic.Disable())
            {
                var current = Database.Query <RuleTypeEntity>().Where(r => r.Role == rules.Role && r.Resource != null).ToDictionary(a => a.Resource);
                var should  = rules.Rules.Where(a => a.Overriden).ToDictionary(r => r.Resource);

                Synchronizer.Synchronize(should, current,
                                         (type, ar) => ar.Allowed.ToRuleType(rules.Role, type).Save(),
                                         (type, pr) => pr.Delete(),
                                         (type, ar, pr) =>
                {
                    pr.Allowed = ar.Allowed.Fallback !.Value;

                    var shouldConditions = ar.Allowed.Conditions.Select(a => new RuleTypeConditionEmbedded
                    {
                        Allowed   = a.Allowed,
                        Condition = a.TypeCondition,
                    }).ToMList();

                    if (!pr.Conditions.SequenceEqual(shouldConditions))
                    {
                        pr.Conditions = shouldConditions;
                    }

                    if (pr.IsGraphModified)
                    {
                        pr.Save();
                    }
                });
        /// <summary>
        /// Redirect user to Respective module based on login infomation
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public async Task <ActionResult> Login(FormCollection form)
        {
            try
            {
                AuthLogic logic       = new AuthLogic();
                var       userSession = await logic.WebLogin(form["email"], form["password"]);

                if (userSession != null)
                {
                    HttpCookie authCookie = new HttpCookie(Literals.CookieToken);
                    authCookie[Literals.APIToken] = userSession.AuthToken;
                    authCookie.Expires            = DateTime.Now.AddDays(100);
                    authCookie.Secure             = false;
                    Response.Cookies.Add(authCookie);
                    if (userSession.Attende.AdminInfo?.UserRole == (int)enUserRole.Moderator && userSession.IsActive == true)
                    {
                        return(RedirectToAction("Index", "Moderator"));
                    }
                    if (userSession.Attende.AdminInfo?.UserRole == (int)enUserRole.EventManager && userSession.IsActive == true)
                    {
                        return(RedirectToAction("Index", "EventManager"));
                    }
                    return(RedirectToAction("Index", "Home"));
                }
            }
            catch (Exception ex)
            {
                Helpers.LogError("Login failed", ex);
                ViewData[Literals.ErrorKey] = ex.Message;
                return(RedirectToAction("index"));
            }
            return(RedirectToAction("index"));
        }
Example #9
0
        public ActionResult <LoginResponse> ChangePassword([Required, FromBody] ChangePasswordRequest request)
        {
            if (string.IsNullOrEmpty(request.oldPassword))
            {
                return(ModelError("oldPassword", AuthMessage.PasswordMustHaveAValue.NiceToString()));
            }

            if (string.IsNullOrEmpty(request.newPassword))
            {
                return(ModelError("newPassword", AuthMessage.PasswordMustHaveAValue.NiceToString()));
            }

            var user = UserEntity.Current;

            if (!user.PasswordHash.SequenceEqual(Security.EncodePassword(request.oldPassword)))
            {
                return(ModelError("oldPassword", AuthMessage.InvalidPassword.NiceToString()));
            }

            user.PasswordHash = Security.EncodePassword(request.newPassword);
            using (AuthLogic.Disable())
                user.Execute(UserOperation.Save);

            return(new LoginResponse {
                userEntity = user, token = AuthTokenServer.CreateToken(UserEntity.Current)
            });
        }
Example #10
0
        public async Task GenerateJWTTest_ReturnUser()
        {
            var options = new DbContextOptionsBuilder <AppDbContext>()
                          .UseInMemoryDatabase(databaseName: "UserDatabase")
                          .Options;

            using (var context = new AppDbContext(options))
            {
                context.ct_user.Add(new User {
                    Id = 1, Email = "*****@*****.**", Name = "jeremey", Password = password
                });
                context.SaveChanges();
            }

            using (var context = new AppDbContext(options))
            {
                userrepos = new UserRepos(context);
                AppSettings inputappsetings = new AppSettings();
                inputappsetings.Secret = "thisisasecret";

                appsettings = Options.Create(inputappsetings);
                AuthLogic      authlogic = new AuthLogic(userrepos, appsettings);
                LoginViewModel user2     = new LoginViewModel();
                user2.Email    = "*****@*****.**";
                user2.Password = "******";
                User user;

                user = await authlogic.GenerateJWT(user2);

                Assert.AreEqual(user.Email, user2.Email);
            }
        }
Example #11
0
        static MapColorProvider[] GetMapColors()
        {
            if (!BasicPermission.AdminRules.IsAuthorized())
            {
                return(new MapColorProvider[0]);
            }

            var roleRules = AuthLogic.RolesInOrder().ToDictionary(r => r,
                                                                  r => TypeAuthLogic.GetTypeRules(r).Rules.ToDictionary(a => a.Resource.CleanName, a => a.Allowed));

            return(roleRules.Keys.Select((r, i) => new MapColorProvider
            {
                Name = "role-" + r.Key(),
                NiceName = "Role - " + r.ToString(),
                AddExtra = t =>
                {
                    TypeAllowedAndConditions tac = roleRules[r].TryGetC(t.typeName);

                    if (tac == null)
                    {
                        return;
                    }

                    t.extra["role-" + r.Key() + "-ui"] = GetName(ToStringList(tac, userInterface: true));
                    t.extra["role-" + r.Key() + "-db"] = GetName(ToStringList(tac, userInterface: false));
                    t.extra["role-" + r.Key() + "-tooltip"] = ToString(tac.Fallback) + "\n" + (tac.Conditions.IsNullOrEmpty() ? null :
                                                                                               tac.Conditions.ToString(a => a.TypeCondition.NiceToString() + ": " + ToString(a.Allowed), "\n") + "\n");
                },
                Order = 10,
            }).ToArray());
        }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string AuthToken = string.Empty;

            if (filterContext.ActionParameters.ContainsKey(Literals.APIToken) && filterContext.ActionParameters[Literals.APIToken] != null)
            {
                AuthToken = filterContext.ActionParameters[Literals.APIToken].ToString();
            }
            if (string.IsNullOrEmpty(AuthToken) && Request.Cookies[Literals.CookieToken] != null)
            {
                AuthToken = Request.Cookies[Literals.CookieToken][Literals.APIToken];
            }

            if (!string.IsNullOrEmpty(AuthToken))
            {
                AuthLogic authLogic = new AuthLogic();
                _currentSession = authLogic.CheckSession(AuthToken);
                if (_currentSession != null)
                {
                    ViewBag.AppUser = _currentSession.Attende;
                }
                //set current session variale here
            }
            base.OnActionExecuting(filterContext);
        }
        public async Task <CredentialMakeResult> MakeCredential([Required, FromBody] MakeCredentialsRequest request)
        {
            using (AuthLogic.Disable())
            {
                var optionsEntity = Database.Retrieve <WebAuthnMakeCredentialsOptionsEntity>(request.CreateOptionsId);

                var options = CredentialCreateOptions.FromJson(optionsEntity.Json);

                var result = await fido2.MakeNewCredentialAsync(request.AttestationRawResponse, options, async (args) =>
                {
                    return(!(await Database.Query <WebAuthnCredentialEntity>().AnyAsync(c => c.CredentialId == args.CredentialId)));
                });

                if (result.Status != "ok")
                {
                    throw new InvalidOperationException(options.ErrorMessage);
                }

                new WebAuthnCredentialEntity
                {
                    CredentialId = result.Result.CredentialId,
                    PublicKey    = result.Result.PublicKey,
                    User         = Lite.ParsePrimaryKey <UserEntity>(Encoding.UTF8.GetString(result.Result.User.Id)),
                    Counter      = (int)result.Result.Counter,
                    CredType     = result.Result.CredType,
                    Aaguid       = result.Result.Aaguid,
                }.Save();

                return(result);
            }
        }
Example #14
0
        public static MainWindowProxy OpenAndLogin(string userName, string password)
        {
            AutomationElement loginElement = FindOpenWindow("Welcome to Southwind");

            Process process = null;

            if (loginElement == null)
            {
                process = Process.Start(@"D:\Signum\Southwind\Southwind.Windows\bin\Debug\Southwind.Windows.exe");

                process.WaitForInputIdle();
                loginElement = AutomationElement.RootElement.WaitChild(a => a.Current.ProcessId == process.Id && a.Current.ClassName == "Login", 5000);
            }

            var result = new MainWindowProxy(LoginWindowProxy.LoginAndContinue(loginElement, userName, password));

            if (process != null)
            {
                result.Disposed += () => process.Kill();
            }

            CultureInfoEntity culture = AuthLogic.RetrieveUser(userName).CultureInfo;

            Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = culture?.ToCultureInfo() ?? new CultureInfo("en-US");

            return(result);
        }
Example #15
0
 public FacadeController(AuthLogic authLogic, TurnLogic turnLogic)
 {
     _authLogic         = authLogic;
     _turnLogic         = turnLogic;
     drawcardcontroller = new DrawCardController();
     strategy           = new Strategy();
 }
Example #16
0
        static MapColorProvider[] GetMapColors()
        {
            if (!BasicPermission.AdminRules.IsAuthorized())
            {
                return(new MapColorProvider[0]);
            }

            var roleRules = AuthLogic.RolesInOrder().ToDictionary(r => r,
                                                                  r => TypeAuthLogic.GetTypeRules(r).Rules.ToDictionary(a => Navigator.ResolveWebTypeName(a.Resource.ToType()), a => a.Allowed));

            return(roleRules.Keys.Select((r, i) => new MapColorProvider
            {
                Name = "role-" + r.Key(),
                NiceName = "Role - " + r.ToString(),
                GetJsProvider = ColorModule["authAdminColor"](MapClient.NodesConstant, "role-" + r.Key()),
                AddExtra = t =>
                {
                    TypeAllowedAndConditions tac = roleRules[r].TryGetC(t.webTypeName);

                    if (tac == null)
                    {
                        return;
                    }

                    t.extra["role-" + r.Key() + "-ui"] = GetName(ToStringList(tac, userInterface: true));
                    t.extra["role-" + r.Key() + "-db"] = GetName(ToStringList(tac, userInterface: false));
                    t.extra["role-" + r.Key() + "-tooltip"] = ToString(tac.Fallback) + "\n" + (tac.Conditions.IsNullOrEmpty() ? null :
                                                                                               tac.Conditions.ToString(a => a.TypeCondition.NiceToString() + ": " + ToString(a.Allowed), "\n") + "\n");
                },
                Defs = i == 0 ? GetAllGradients(roleRules) : null,
                Order = 10,
            }).ToArray());
        }
Example #17
0
        public ActionResult Create(IFormCollection collection)
        {
            try
            {
                var    courseName  = new StringValues();
                var    description = new StringValues();
                var    token       = new StringValues();
                string id          = "";
                if (collection.TryGetValue("CourseName", out courseName) && collection.TryGetValue("Description", out description) && collection.TryGetValue("token", out token))
                {
                    var username = AuthLogic.CheckToken(token.ToString());
                    if (username == "")
                    {
                        throw new Exception("NotAuthorized");
                    }

                    // save course
                    id = Course.CreateCourse(courseName.ToString(), description.ToString(), username);
                }
                return(RedirectToAction("Details", new { token = token, id = id }));
            }
            catch
            {
                return(View());
            }
        }
Example #18
0
        private void LoginHandler56(List <object> data)
        {
            Network.AuthServer.TransactionCounter = (uint)data[1];

            if (AuthLogic.Login(System.BitConverter.ToString((byte[])data[2]), System.BitConverter.ToString((byte[])data[3]), (string)data[5]))
            {
                Game.State = GameState.CharacterScreen;

                Game.Player.Account.SendCharacters();

                Network.AuthServer.Send(AuthServerMessage.Gui, Network.AuthServer.TransactionCounter, (ushort)0);

                Game.Player.FriendList.Init();
                Network.AuthServer.Send(AuthServerMessage.PlayerStatus, Network.AuthServer.TransactionCounter, (uint)Game.Player.Status);

                Network.AuthServer.Send(AuthServerMessage.AccountPermissions,
                                        Network.AuthServer.TransactionCounter,
                                        2,
                                        4,
                                        new byte[] { 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                                        new byte[] { 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0C, 0x00 },
                                        new byte[16],      // account id
                                        new byte[16],      // last played character id
                                        8,                 // account management system version
                                        Game.Player.Account.SerializeUnlocks(),
                                        (byte)23,          // accepted eula
                                        0);                // enable name change (requires name change credits)

                Network.AuthServer.SendTransactionSuccessCode(TransactionSuccessCode.Success);
            }
            else
            {
                Network.AuthServer.SendTransactionSuccessCode(TransactionSuccessCode.LoginFailed);
            }
        }
Example #19
0
        Dictionary <Lite <RoleEntity>, RoleAllowedCache> NewCache()
        {
            using (AuthLogic.Disable())
                using (new EntityCache(EntityCacheType.ForceNewSealed))
                {
                    List <Lite <RoleEntity> > roles = AuthLogic.RolesInOrder().ToList();

                    var rules = Database.Query <RuleTypeEntity>().ToList();

                    var errors = GraphExplorer.FullIntegrityCheck(GraphExplorer.FromRoots(rules));
                    if (errors != null)
                    {
                        throw new IntegrityCheckException(errors);
                    }

                    Dictionary <Lite <RoleEntity>, Dictionary <Type, TypeAllowedAndConditions> > realRules =
                        rules.AgGroupToDictionary(ru => ru.Role, gr => gr
                                                  .SelectCatch(ru => KeyValuePair.Create(TypeLogic.EntityToType.GetOrThrow(ru.Resource), ru.ToTypeAllowedAndConditions()))
                                                  .ToDictionaryEx());

                    Dictionary <Lite <RoleEntity>, RoleAllowedCache> newRules = new Dictionary <Lite <RoleEntity>, RoleAllowedCache>();
                    foreach (var role in roles)
                    {
                        var related = AuthLogic.RelatedTo(role);

                        newRules.Add(role, new RoleAllowedCache(role, merger, related.Select(r => newRules.GetOrThrow(r)).ToList(), realRules.TryGetC(role)));
                    }

                    return(newRules);
                }
        }
Example #20
0
    public QueryAllowed Merge(object key, Lite <RoleEntity> role, IEnumerable <KeyValuePair <Lite <RoleEntity>, QueryAllowed> > baseValues)
    {
        QueryAllowed best = AuthLogic.GetMergeStrategy(role) == MergeStrategy.Union ?
                            Max(baseValues.Select(a => a.Value)) :
                            Min(baseValues.Select(a => a.Value));

        var maxUp = QueryAuthLogic.MaxAutomaticUpgrade.TryGetS(key);

        if (maxUp.HasValue && maxUp <= best)
        {
            return(best);
        }

        if (!BasicPermission.AutomaticUpgradeOfQueries.IsAuthorized(role))
        {
            return(best);
        }

        if (baseValues.Where(a => a.Value.Equals(best)).All(a => GetDefault(key, a.Key).Equals(a.Value)))
        {
            var def = GetDefault(key, role);

            return(maxUp.HasValue && maxUp <= def ? maxUp.Value : def);
        }

        return(best);
    }
Example #21
0
        static string RefreshToken(AuthToken oldToken, out UserEntity newUser)
        {
            newUser = AuthLogic.Disable().Using(_ => Database.Query <UserEntity>().SingleOrDefaultEx(u => u.Id == oldToken.User.Id));

            if (newUser == null)
            {
                throw new AuthenticationException(AuthMessage.TheUserIsNotLongerInTheDatabase.NiceToString());
            }

            if (newUser.State == UserState.Disabled)
            {
                throw new AuthenticationException(AuthMessage.User0IsDisabled.NiceToString(newUser));
            }

            if (newUser.UserName != oldToken.User.UserName)
            {
                throw new AuthenticationException(AuthMessage.InvalidUsername.NiceToString());
            }

            if (!newUser.PasswordHash.EmptyIfNull().SequenceEqual(oldToken.User.PasswordHash.EmptyIfNull()))
            {
                throw new AuthenticationException(AuthMessage.InvalidPassword.NiceToString());
            }

            AuthToken newToken = new AuthToken
            {
                User         = newUser,
                CreationDate = TimeZoneManager.Now,
            };

            var result = SerializeToken(newToken);

            return(result);
        }
Example #22
0
        public string SetCurrentCulture([Required, FromBody] Lite <CultureInfoEntity> culture)
        {
            var ci = ExecutionMode.Global().Using(_ => culture.RetrieveAndRemember().ToCultureInfo());

            if (UserEntity.Current != null && !UserEntity.Current.Is(AuthLogic.AnonymousUser)) //Won't be used till next refresh
            {
                using (AuthLogic.Disable())
                    using (OperationLogic.AllowSave <UserEntity>())
                    {
                        var user = UserEntity.Current.ToLite().RetrieveAndRemember();
                        user.CultureInfo   = culture.RetrieveAndRemember();
                        UserEntity.Current = user;
                        user.Save();
                    }
            }

            ControllerContext.HttpContext.Response.Cookies.Append("language", ci.Name, new CookieOptions
            {
                Expires     = DateTimeOffset.Now.AddYears(10),
                Path        = "/",
                IsEssential = true,
                Domain      = Request.Host.Host
            });
            return(ci.Name);
        }
Example #23
0
        private void MoveFriendListEntryHandler(List <object> objects)
        {
            bool success = AuthLogic.MoveFriend(new Guid((byte[])objects[3]), (FriendList.Type)(uint) objects[2]);

            Network.AuthServer.TransactionCounter = (uint)objects[1];
            Network.AuthServer.SendTransactionSuccessCode(success ? TransactionSuccessCode.Success : TransactionSuccessCode.Aborted);
        }
Example #24
0
    public static ResetPasswordRequestEntity SendResetPasswordRequestEmail(string email)
    {
        UserEntity?user;

        using (AuthLogic.Disable())
        {
            user = Database
                   .Query <UserEntity>()
                   .SingleOrDefault(u => u.Email == email && u.State != UserState.Deactivated);

            if (user == null)
            {
                throw new ApplicationException(AuthEmailMessage.EmailNotFound.NiceToString());
            }
        }

        try
        {
            var request = ResetPasswordRequest(user);

            string url = EmailLogic.Configuration.UrlLeft + @"/auth/ResetPassword?code={0}".FormatWith(request.Code);

            using (AuthLogic.Disable())
                new ResetPasswordRequestEmail(request, url).SendMail();

            return(request);
        }
        catch (Exception ex)
        {
            ex.LogException();
            throw new ApplicationException(LoginAuthMessage.AnErrorOccurredRequestNotProcessed.NiceToString());
        }
    }
Example #25
0
        private void PlayRequest(List <object> objects)
        {
            Network.AuthServer.TransactionCounter = (uint)objects[1];
            var mapId = (uint)objects[3];

            if (mapId != 0)
            {
                AuthLogic.Play((Map)mapId);
            }
            else
            {
                Game.State = GameState.CharacterCreation;

                Network.AuthServer.Send(AuthServerMessage.Dispatch,
                                        Network.AuthServer.TransactionCounter,
                                        0,
                                        mapId,
                                        new byte[]
                {
                    0x02, 0x00, 0x23, 0x98, 0x22, 0x22, 0x22, 0x22,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                },
                                        0);
            }
        }
Example #26
0
        private static SignumAuthenticationResult ApiKeyAuthenticator(HttpActionContext ctx)
        {
            var nvp = ctx.Request.RequestUri.ParseQueryString();
            IEnumerable <string> queryKeys = ctx.Request.RequestUri
                                             .ParseQueryString()
                                             .GetValues(RestApiKeyLogic.ApiKeyQueryParameter)?
                                             .Distinct() ?? Enumerable.Empty <string>();

            IEnumerable <string> headerKeys;

            ctx.Request.Headers.TryGetValues(RestApiKeyLogic.ApiKeyHeaderParameter, out headerKeys);

            var keys = queryKeys.Union(headerKeys ?? Enumerable.Empty <string>());

            if (keys.Count() == 1)
            {
                using (AuthLogic.Disable())
                {
                    var user = RestApiKeyLogic.RestApiKeyCache.Value.GetOrThrow(keys.Single(), $"Could not authenticate with the API Key {keys.Single()}.").User.Retrieve();
                    return(new SignumAuthenticationResult {
                        User = user
                    });
                }
            }
            else if (keys.Count() > 1)
            {
                throw new AuthenticationException("Request contains multiple API Keys. Please use a single API Key per request for authentication.");
            }

            return(null);
        }
Example #27
0
        public void GenerateEnvironment()
        {
            var authRules = XDocument.Load(@"..\..\..\..\Southwind.Load\AuthRules.xml");

            SouthwindEnvironment.Start();

            Administrator.TotalGeneration();

            Schema.Current.Initialize();

            OperationLogic.AllowSaveGlobally = true;

            using (AuthLogic.Disable())
            {
                SouthwindEnvironment.LoadBasics();

                AuthLogic.LoadRoles(authRules);
                SouthwindEnvironment.LoadEmployees();
                SouthwindEnvironment.LoadUsers();
                SouthwindEnvironment.LoadProducts();
                SouthwindEnvironment.LoadCustomers();
                SouthwindEnvironment.LoadShippers();

                AuthLogic.ImportRulesScript(authRules, interactive: false) !.PlainSqlCommand().ExecuteLeaves();
            }

            OperationLogic.AllowSaveGlobally = false;
        }
Example #28
0
        internal XElement ExportXml(List <Type>?allTypes)
        {
            var rules = runtimeRules.Value;

            return(new XElement("Types",
                                (from r in AuthLogic.RolesInOrder()
                                 let rac = rules.GetOrThrow(r)
                                           select new XElement("Role",
                                                               new XAttribute("Name", r.ToString()),
                                                               from k in allTypes ?? (rac.DefaultDictionary().OverrideDictionary?.Keys).EmptyIfNull()
                                                               let allowedBase = rac.GetAllowedBase(k)
                                                                                 let allowed = rac.GetAllowed(k)
                                                                                               where allTypes != null || !allowed.Equals(allowedBase)
                                                                                               let resource = TypeLogic.GetCleanName(k)
                                                                                                              orderby resource
                                                                                                              select new XElement("Type",
                                                                                                                                  new XAttribute("Resource", resource),
                                                                                                                                  new XAttribute("Allowed", allowed.Fallback.ToString()),
                                                                                                                                  from c in allowed.Conditions
                                                                                                                                  let conditionName = c.TypeCondition.Key
                                                                                                                                                      orderby conditionName
                                                                                                                                                      select new XElement("Condition",
                                                                                                                                                                          new XAttribute("Name", conditionName),
                                                                                                                                                                          new XAttribute("Allowed", c.Allowed.ToString()))
                                                                                                                                  )
                                                               )
                                )));
        }
Example #29
0
        public IActionResult Login(IFormCollection collection)
        {
            var    email = new StringValues();
            var    pass  = new StringValues();
            string token = "";

            if (collection.TryGetValue("Email", out email) && collection.TryGetValue("Password", out pass))
            {
                try
                {
                    var auth = new AuthLogic();
                    auth.Email    = email.ToString();
                    auth.Password = pass.ToString();
                    token         = auth.Login();
                    return(RedirectToAction("Index", "Profile", new { token = token }));
                }
                catch (Exception)
                {
                    return(Error());
                }
            }
            else
            {
                return(Error());
            }
        }
Example #30
0
        /// <summary>
        /// Constructor
        /// </summary>
        public override void OnActionExecuting(HttpActionContext context)
        {
            AuthLogic    authLogic = new AuthLogic(db);
            JSendMessage json;

            var header = context.Request.Headers.SingleOrDefault(x => x.Key == "token");

            bool valid, isAdmin, okDate;

            if (header.Value == null)
            {
                valid = false;
            }
            else
            {
                // Tokenul apartine unui admin
                isAdmin = authLogic.VerifyAdminToken(header.Value.First());

                // Tokenul este valid
                okDate = authLogic.VerifyTokenDate(header.Value.First());

                valid = isAdmin && okDate;
            }

            if (!valid)
            {
                json             = new JSendMessage("fail", "Invalid Authorization Key");
                context.Response = context.Request.CreateResponse(HttpStatusCode.Forbidden, json);
            }
        }