Beispiel #1
0
 public bool Activate(Guid token)
 {
     if (!Guid.Empty.Equals(token))
     {
         if (resetTokens.ContainsKey(token))
         {
             IIdentityProvider idProv = IdentityManager.Instance.GetProvider(ctx);
             UserIdentityBase  userId = idProv.Get(resetTokens[token].Token);
             if (userId != null && userId.UserState != UserState.Dead)
             {
                 resetTokens.Remove(token);
                 userId.UserState = UserState.Active;
                 if (idProv.Update(userId))
                 {
                     IRoleProvider roles = AuthorizationManager.Instance.GetRoleProvider(ctx);
                     if (roles != null)
                     {
                         Role r = roles.Get(new Guid("a55c4810-de06-466e-8f30-4f02b138186f"));
                         if (r != null)
                         {
                             return(roles.AddToRole(r, userId));
                         }
                     }
                 }
             }
         }
     }
     return(false);
 }
Beispiel #2
0
 public bool ChangePass(Guid sid, string user, Guid token, string newPass)
 {
     if (!Guid.Empty.Equals(sid))
     {
         if (resetTokens.ContainsKey(token))
         {
             ModuleRuntimeSession sess = Session.Prov.Get(sid);
             if (sess != null)
             {
                 IIdentityProvider idProv = IdentityManager.Instance.GetProvider(ctx);
                 UserIdentityBase  userId = idProv.Get(resetTokens[token].Token);
                 if (userId != null && userId.UserState != UserState.Dead)
                 {
                     IAuthenticationProvider authProv = AuthenticationManager.Instance.GetProvider(ctx);
                     if (authProv.AddCredential(userId, new UserPasswordCredential(user, newPass)))
                     {
                         resetTokens.Remove(token);
                         sess.SetUserBinding(userId.Uid, sess.Binding);
                         Session.Prov.Update(sess);
                         return(true);
                     }
                 }
             }
         }
     }
     return(false);
 }
Beispiel #3
0
 public UserIdentityBase Get(Guid userId, UserType type)
 {
     if (!Guid.Empty.Equals(userId) && CanGet())
     {
         NpgsqlCommand cmd = Db.GetCmd(Db.ConnectionString);
         cmd.CommandText = Db.Select + Db.SelectByIdType;
         cmd.Parameters.AddWithValue("id", userId);
         cmd.Parameters.AddWithValue("ut", (int)type);
         NpgsqlDataReader rdr = Db.ExecuteReader(cmd);
         UserIdentityBase o   = null;
         if (rdr != null)
         {
             try
             {
                 if (rdr.Read())
                 {
                     o = UserBuilder.Instance.Build(rdr);
                 }
                 if (cmd.Connection.State == System.Data.ConnectionState.Open)
                 {
                     cmd.Connection.Close();
                 }
             }
             catch
             { }
             finally
             {
                 cmd.Dispose();
             }
         }
         return(o);
     }
     return(null);
 }
Beispiel #4
0
 public WxAppUserIdentity(UserIdentityBase user = null)
 {
     if (user != null)
     {
         IsAuthenticated = true;
         Name            = user.Name;
         UserId          = user.UserId;
     }
 }
Beispiel #5
0
        public static bool IsActive(this IIdentityProvider provider, IUserIdentity user)
        {
            if (provider != null && user != null)
            {
                UserIdentityBase uib = provider.Get(user.Uid);
                if (uib != null)
                {
                    return(uib.UserState == UserState.Active);
                }
            }

            return(false);
        }
Beispiel #6
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl, localUrl);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        if (meth.StartsWith(Taxonomy, StringComparison.OrdinalIgnoreCase))
                        {
                            TaxonomyHandler.Handle(ctx, meth.Substring(Taxonomy.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Domain, StringComparison.OrdinalIgnoreCase))
                        {
                            TaxaDomainHandler.Handle(ctx, meth.Substring(Domain.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(UnitType, StringComparison.OrdinalIgnoreCase))
                        {
                            TaxaUnitTypeHandler.Handle(ctx, meth.Substring(UnitType.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Unit, StringComparison.OrdinalIgnoreCase))
                        {
                            TaxaUnitHandler.Handle(ctx, meth.Substring(Unit.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(CommonName, StringComparison.OrdinalIgnoreCase))
                        {
                            TaxaCommonNameHandler.Handle(ctx, meth.Substring(CommonName.Length), context, cancel);
                            return;
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
                    return;
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #7
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null && context.Request.Method == "POST") //all we support is post
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl, localUrl);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        JObject body = JsonUtils.ParseBody(context.Request) as JObject;

                        if (body != null)
                        {
                            if (meth.Equals(get, StringComparison.OrdinalIgnoreCase))
                            {
                                Get(context, ctx, body);
                                return;
                            }
                            if (meth.Equals(add, StringComparison.OrdinalIgnoreCase))
                            {
                                Add(context, ctx, body);
                                return;
                            }
                            if (meth.Equals(delete, StringComparison.OrdinalIgnoreCase))
                            {
                                Delete(context, ctx, body);
                                return;
                            }
                        }
                        else
                        {
                            GetForUser(context, ctx);
                            return;
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
                    return;
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #8
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl, localUrl);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        JToken dat = JsonUtils.GetDataPayload(context.Request);

                        if (meth.StartsWith(Create, StringComparison.OrdinalIgnoreCase))
                        {
                            DetGeneralHandler.Create(ctx, dat, context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Update, StringComparison.OrdinalIgnoreCase))
                        {
                            DetGeneralHandler.Update(ctx, dat, context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Get, StringComparison.OrdinalIgnoreCase))
                        {
                            DetGeneralHandler.Get(ctx, dat, context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Delete, StringComparison.OrdinalIgnoreCase))
                        {
                            DetGeneralHandler.Delete(ctx, dat, context, cancel);
                            return;
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
                    return;
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #9
0
        public bool Update(UserIdentityBase identity)
        {
            if (identity != null && CanUpdate(identity))
            {
                NpgsqlCommand cmd = Db.GetCmd(Db.ConnectionString);
                cmd.CommandText = Db.Update;

                cmd.Parameters.AddWithValue("id", identity.Uid);
                cmd.Parameters.AddWithValue("ut", (int)identity.UserType);
                cmd.Parameters.AddWithValue("us", (int)identity.UserState);
                cmd.Parameters.Add(Db.GetEAParam(identity.ExpiresAt, System.Data.ParameterDirection.Input));
                cmd.Parameters.AddWithValue("name", identity.Name);

                Db.ExecuteNonQuery(cmd);
                return(true);
            }
            return(false);
        }
Beispiel #10
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl, localUrl);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        if (meth.StartsWith(Orgs, StringComparison.OrdinalIgnoreCase))
                        {
                            OrgHandler.Handle(ctx, meth.Substring(Orgs.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Alias, StringComparison.OrdinalIgnoreCase))
                        {
                            AliasHandler.Handle(ctx, meth.Substring(Alias.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(AliasScheme, StringComparison.OrdinalIgnoreCase))
                        {
                            SchemeHandler.Handle(ctx, meth.Substring(AliasScheme.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Hierarchy, StringComparison.OrdinalIgnoreCase))
                        {
                            HierarchyHandler.Handle(ctx, meth.Substring(Hierarchy.Length), context, cancel);
                            return;
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
                    return;
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #11
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl, localUrl);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        if (meth.StartsWith(Activities, StringComparison.OrdinalIgnoreCase))
                        {
                            FieldActivityHandler.Handle(ctx, meth.Substring(Activities.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Teams, StringComparison.OrdinalIgnoreCase))
                        {
                            FieldTeamHandler.Handle(ctx, meth.Substring(Teams.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Trips, StringComparison.OrdinalIgnoreCase))
                        {
                            FieldTripHandler.Handle(ctx, meth.Substring(Trips.Length), context, cancel);
                            return;
                        }
                        if (meth.StartsWith(Samples, StringComparison.OrdinalIgnoreCase))
                        {
                            SampleEventHandler.Handle(ctx, meth.Substring(Samples.Length), context, cancel);
                            return;
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
                    return;
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #12
0
 public override void Handle(HttpContext context, CancellationToken cancel)
 {
     if (context != null && AuthorizationManager.Instance.State == Osrs.Runtime.RunState.Running && context.Request.Method == "POST") //all we support is post
     {
         UserIdentityBase user = Security.Session.GetUser(context);
         if (user != null)
         {
             UserSecurityContext ctx  = new UserSecurityContext(user);
             IRoleProvider       prov = AuthorizationManager.Instance.GetRoleProvider(ctx);
             if (prov != null)
             {
                 IEnumerable <Permission> perms = prov.GetPermissions(user);
                 if (perms != null)
                 {
                     JArray orgs = Jsonifier.ToJson(perms);
                     if (orgs != null)
                     {
                         RestUtils.Push(context.Response, JsonOpStatus.Ok, orgs);
                     }
                     else
                     {
                         RestUtils.Push(context.Response, JsonOpStatus.Failed);
                     }
                 }
                 else
                 {
                     RestUtils.Push(context.Response, JsonOpStatus.Ok, "[]");
                 }
             }
             else
             {
                 RestUtils.Push(context.Response, JsonOpStatus.Failed, "No provider");
             }
             return;
         }
         else
         {
             context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
         }
     }
     context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
 }
Beispiel #13
0
 public IEnumerable <UserIdentityBase> Get(string name, UserType type)
 {
     if (!string.IsNullOrEmpty(name) && CanGet())
     {
         NpgsqlCommand cmd = Db.GetCmd(Db.ConnectionString);
         cmd.CommandText = Db.Select + Db.SelectByNameType;
         cmd.Parameters.AddWithValue("name", name);
         cmd.Parameters.AddWithValue("ut", (int)type);
         NpgsqlDataReader        rdr = Db.ExecuteReader(cmd);
         List <UserIdentityBase> o   = new List <UserIdentityBase>();
         if (rdr != null)
         {
             try
             {
                 while (rdr.Read())
                 {
                     UserIdentityBase u = UserBuilder.Instance.Build(rdr);
                     if (u != null)
                     {
                         o.Add(u);
                     }
                 }
                 if (cmd.Connection.State == System.Data.ConnectionState.Open)
                 {
                     cmd.Connection.Close();
                 }
             }
             catch
             { }
             finally
             {
                 cmd.Dispose();
             }
         }
         return(o);
     }
     return(null);
 }
Beispiel #14
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl + "/", localUrl);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        Handle(ctx, meth, context, cancel);
                    }
                }
                else
                {
                    context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #15
0
 public IEnumerable <UserIdentityBase> Get()
 {
     if (CanGet())
     {
         NpgsqlCommand cmd = Db.GetCmd(Db.ConnectionString);
         cmd.CommandText = Db.Select;
         NpgsqlDataReader        rdr = Db.ExecuteReader(cmd);
         List <UserIdentityBase> o   = new List <UserIdentityBase>();
         if (rdr != null)
         {
             try
             {
                 while (rdr.Read())
                 {
                     UserIdentityBase u = UserBuilder.Instance.Build(rdr);
                     if (u != null)
                     {
                         o.Add(u);
                     }
                 }
                 if (cmd.Connection.State == System.Data.ConnectionState.Open)
                 {
                     cmd.Connection.Close();
                 }
             }
             catch
             { }
             finally
             {
                 cmd.Dispose();
             }
         }
         return(o);
     }
     return(null);
 }
Beispiel #16
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl, localUrl);
                    meth = meth.Substring(1);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        if (context.Request.Method == "POST")
                        {
                            if (meth.Equals("request", StringComparison.OrdinalIgnoreCase))
                            {
                                try
                                {
                                    HashSet <CompoundIdentity> affilsRead  = null;
                                    HashSet <CompoundIdentity> affilsWrite = null;
                                    HashSet <string>           rolesRead   = null;
                                    HashSet <string>           rolesWrite  = null;
                                    string reason = null;
                                    JToken token  = JsonUtils.GetDataPayload(context.Request);
                                    if (token != null)
                                    {
                                        if (token["affils"] != null)
                                        {
                                            JToken affils = token["affils"];
                                            if (affils["read"] != null)
                                            {
                                                affilsRead = JsonUtils.ToIds(affils["read"]);
                                            }
                                            if (affils["write"] != null)
                                            {
                                                affilsWrite = JsonUtils.ToIds(affils["write"]);
                                            }
                                        }
                                        if (token["roles"] != null)
                                        {
                                            JToken roles = token["roles"];
                                            if (roles["read"] != null)
                                            {
                                                rolesRead = ToStrings(roles["read"] as JArray);
                                            }
                                            if (roles["write"] != null)
                                            {
                                                rolesWrite = ToStrings(roles["write"] as JArray);
                                            }
                                        }
                                        if (token["reason"] != null)
                                        {
                                            reason = token["reason"].ToString();
                                        }
                                    }
                                    Guid currentUser = ctx.User.Uid;
                                    if (currentUser != null)
                                    {
                                        if (affilsRead != null)
                                        {
                                            foreach (CompoundIdentity id in affilsRead)
                                            {
                                                if (!id.IsNullOrEmpty())
                                                {
                                                    CreateAffil(currentUser, id, false, reason);
                                                }
                                            }
                                        }
                                        if (affilsWrite != null)
                                        {
                                            foreach (CompoundIdentity id in affilsWrite)
                                            {
                                                if (!id.IsNullOrEmpty())
                                                {
                                                    CreateAffil(currentUser, id, true, reason);
                                                }
                                            }
                                        }
                                        if (rolesRead != null)
                                        {
                                            foreach (string role in rolesRead)
                                            {
                                                if (!string.IsNullOrEmpty(role))
                                                {
                                                    CreateRole(currentUser, role, reason);
                                                }
                                            }
                                        }
                                        if (rolesWrite != null)
                                        {
                                            foreach (string role in rolesWrite)
                                            {
                                                if (!string.IsNullOrEmpty(role))
                                                {
                                                    CreateRole(currentUser, role, reason);
                                                }
                                            }
                                        }
                                    }
                                    RestUtils.Push(context.Response, JsonOpStatus.Ok);
                                }
                                catch
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #17
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl, localUrl);
                    meth = meth.Substring(1);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        if (context.Request.Method == "POST")
                        {
                            if (meth.Equals("deployments", StringComparison.OrdinalIgnoreCase))
                            {
                                try
                                {
                                    HashSet <CompoundIdentity> eventIds      = null;
                                    HashSet <CompoundIdentity> deploymentIds = null;
                                    HashSet <CompoundIdentity> siteIds       = null;
                                    DateTime?start = null;
                                    DateTime?end   = null;

                                    JToken token = JsonUtils.GetDataPayload(context.Request);
                                    if (token != null)
                                    {
                                        if (token["events"] != null)
                                        {
                                            eventIds = JsonUtils.ToIds(token["events"]);
                                        }

                                        if (token["deployments"] != null)
                                        {
                                            deploymentIds = JsonUtils.ToIds(token["deployments"]);
                                        }

                                        if (token["sites"] != null)
                                        {
                                            siteIds = JsonUtils.ToIds(token["sites"]);
                                        }

                                        if (token["start"] != null)
                                        {
                                            start = JsonUtils.ToDate(token["start"]);
                                        }

                                        if (token["end"] != null)
                                        {
                                            end = JsonUtils.ToDate(token["end"]);
                                        }
                                    }

                                    IWQDeploymentProvider provider = WaterQualityManager.Instance.GetDeploymentProvider(ctx);                                     //filters WQ deployments by user context
                                    if (provider != null)
                                    {
                                        IEnumerable <WaterQualityDeployment> deployments = GetDeployments(provider, eventIds, deploymentIds, siteIds, start, end);
                                        JArray jdeployments = Jsonifier.ToJson(deployments);

                                        if (jdeployments != null)
                                        {
                                            RestUtils.Push(context.Response, JsonOpStatus.Ok, jdeployments.ToString());
                                            return;
                                        }
                                        else
                                        {
                                            RestUtils.Push(context.Response, JsonOpStatus.Ok, "[]");
                                            return;
                                        }
                                    }
                                }
                                catch
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                            }
                            else if (meth.Equals("measurements", StringComparison.OrdinalIgnoreCase))
                            {
                                try
                                {
                                    //TODO: ask about iterative calls for deployments (each deployment is a separate db call)

                                    IWQMeasurementProvider provider = WaterQualityManager.Instance.GetMeasurementProvider(ctx);
                                    if (provider != null)
                                    {
                                        HashSet <CompoundIdentity> eventIds      = null;
                                        HashSet <CompoundIdentity> deploymentIds = null;
                                        HashSet <CompoundIdentity> siteIds       = null;
                                        DateTime?start = null;
                                        DateTime?end   = null;

                                        JToken token = JsonUtils.GetDataPayload(context.Request);
                                        if (token != null)
                                        {
                                            if (token["events"] != null)
                                            {
                                                eventIds = JsonUtils.ToIds(token["events"]);
                                            }

                                            if (token["deployments"] != null)
                                            {
                                                deploymentIds = JsonUtils.ToIds(token["deployments"]);
                                            }

                                            if (token["sites"] != null)
                                            {
                                                siteIds = JsonUtils.ToIds(token["sites"]);
                                            }

                                            if (token["start"] != null)
                                            {
                                                start = JsonUtils.ToDate(token["start"]);
                                            }

                                            if (token["end"] != null)
                                            {
                                                end = JsonUtils.ToDate(token["end"]);
                                            }
                                        }

                                        IWQDeploymentProvider depProvider = WaterQualityManager.Instance.GetDeploymentProvider(ctx);                                         //provider will autofilter WQ deployments by user context
                                        IEnumerable <WaterQualityDeployment> deployments = GetDeployments(depProvider, eventIds, deploymentIds, siteIds, null, null);

                                        List <WaterQualityMeasurement> measurements = new List <WaterQualityMeasurement>();

                                        if (start != null || end != null)
                                        {
                                            DateTime queryStart;
                                            DateTime queryEnd;
                                            if (start == null)
                                            {
                                                queryStart = WQUtils.GlobalMinDate;
                                            }
                                            else
                                            {
                                                queryStart = start.Value;
                                            }

                                            if (end == null)
                                            {
                                                queryEnd = DateTime.UtcNow;
                                            }
                                            else
                                            {
                                                queryEnd = end.Value;
                                            }

                                            foreach (WaterQualityDeployment dep in deployments)
                                            {
                                                measurements.AddRange(provider.Get(dep.Identity, queryStart, queryEnd));
                                            }
                                        }
                                        else
                                        {
                                            foreach (WaterQualityDeployment dep in deployments)
                                            {
                                                measurements.AddRange(provider.Get(dep.Identity));
                                            }
                                        }

                                        JArray jmeasurements = Jsonifier.ToJson(measurements);

                                        if (jmeasurements != null)
                                        {
                                            RestUtils.Push(context.Response, JsonOpStatus.Ok, jmeasurements.ToString());
                                        }
                                        else
                                        {
                                            RestUtils.Push(context.Response, JsonOpStatus.Ok, "[]");
                                        }
                                        return;
                                    }
                                    RestUtils.Push(context.Response, JsonOpStatus.Failed);
                                }
                                catch
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                            }
                            else if (meth.Equals("export", StringComparison.OrdinalIgnoreCase))
                            {
                                try
                                {
                                    HashSet <CompoundIdentity> eventIds      = null;
                                    HashSet <CompoundIdentity> deploymentIds = null;
                                    HashSet <CompoundIdentity> siteIds       = null;
                                    DateTime?start = null;
                                    DateTime?end   = null;

                                    JToken token = JsonUtils.GetDataPayload(context.Request);
                                    if (token != null)
                                    {
                                        if (token["events"] != null)
                                        {
                                            eventIds = JsonUtils.ToIds(token["events"]);
                                        }

                                        if (token["deployments"] != null)
                                        {
                                            deploymentIds = JsonUtils.ToIds(token["deployments"]);
                                        }

                                        if (token["sites"] != null)
                                        {
                                            siteIds = JsonUtils.ToIds(token["sites"]);
                                        }

                                        if (token["start"] != null)
                                        {
                                            start = JsonUtils.ToDate(token["start"]);
                                        }

                                        if (token["end"] != null)
                                        {
                                            end = JsonUtils.ToDate(token["end"]);
                                        }
                                    }

                                    IWQDeploymentProvider  depProvider           = WaterQualityManager.Instance.GetDeploymentProvider(ctx);
                                    IWQMeasurementProvider measProvider          = WaterQualityManager.Instance.GetMeasurementProvider(ctx);
                                    ISiteProvider          siteProvider          = SiteManager.Instance.GetSiteProvider(ctx);
                                    ISampleEventProvider   sampProvider          = FieldActivityManager.Instance.GetSampleEventProvider(ctx);
                                    IOrganizationProvider  orgProvider           = OrganizationManager.Instance.GetOrganizationProvider(ctx);
                                    IFieldTripProvider     fieldTripProvider     = FieldActivityManager.Instance.GetFieldTripProvider(ctx);
                                    IFieldActivityProvider fieldActivityProvider = FieldActivityManager.Instance.GetFieldActivityProvider(ctx);
                                    IProjectProvider       projectProvider       = ProjectManager.Instance.GetProvider(ctx);

                                    if (depProvider != null && measProvider != null && siteProvider != null && sampProvider != null &&
                                        orgProvider != null && fieldTripProvider != null && fieldActivityProvider != null && projectProvider != null)
                                    {
                                        IEnumerable <WaterQualityDeployment>  deployments  = GetDeployments(depProvider, eventIds, deploymentIds, siteIds, null, null);                                       //on export, time filters apply to measurements only
                                        IEnumerable <WaterQualityMeasurement> measurements = GetMeasurements(measProvider, start, end, deployments);

                                        //Get sites and sample events
                                        List <CompoundIdentity>     selected_siteIds  = deployments.Select(x => x.SiteId).ToList();
                                        List <CompoundIdentity>     selected_eventIds = deployments.Select(x => x.SampleEventId).ToList();
                                        IEnumerable <Site>          sitesData         = GetSites(siteProvider, selected_siteIds);
                                        IEnumerable <SamplingEvent> eventsData        = sampProvider.Get(selected_eventIds);

                                        //Get orgs and field trips
                                        List <CompoundIdentity>    selected_orgIds       = eventsData.Select(x => x.PrincipalOrgId).ToList();
                                        List <CompoundIdentity>    selected_fieldTripIds = eventsData.Select(x => x.FieldTripId).ToList();
                                        IEnumerable <Organization> orgData       = orgProvider.Get(selected_orgIds);
                                        IEnumerable <FieldTrip>    fieldTripData = fieldTripProvider.Get(selected_fieldTripIds);

                                        //Get field activities
                                        List <CompoundIdentity>     selected_fieldActivityIds = fieldTripData.Select(x => x.FieldActivityId).ToList();
                                        IEnumerable <FieldActivity> fieldActivityData         = fieldActivityProvider.Get(selected_fieldActivityIds);

                                        //Get projects
                                        List <CompoundIdentity> selected_projectIds = fieldActivityData.Select(x => x.ProjectId).ToList();
                                        IEnumerable <Project>   projectData         = projectProvider.Get(selected_projectIds);

                                        Guid fileId = CreateDeploymentFile(eventsData, deployments, measurements, sitesData,
                                                                           orgData, fieldTripData, fieldActivityData, projectData);

                                        if (fileId != null)
                                        {
                                            JObject o = new JObject();
                                            o.Add("fileid", fileId.ToString());
                                            o.Add("fileext", fileExtension);
                                            RestUtils.Push(context.Response, JsonOpStatus.Ok, o);
                                        }
                                        else
                                        {
                                            RestUtils.Push(context.Response, JsonOpStatus.Failed);
                                        }
                                        return;
                                    }
                                    RestUtils.Push(context.Response, JsonOpStatus.Failed);
                                }
                                catch
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #18
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl, localUrl);
                    meth = meth.Substring(1);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        if (context.Request.Method == "POST")
                        {
                            if (meth.Equals("all", StringComparison.OrdinalIgnoreCase))
                            {
                                Get(ctx, context, cancel);
                                return;
                            }
                            else if (meth.Equals("create", StringComparison.OrdinalIgnoreCase))
                            {
                                try
                                {
                                    JToken         token    = JsonUtils.GetDataPayload(context.Request);
                                    PersonProvider provider = PersonManager.Instance.GetProvider(ctx);
                                    Person         person   = null;
                                    JObject        jperson  = null;

                                    string firstName = token["firstname"].ToString();
                                    string lastName  = token["lastname"].ToString();
                                    JArray contacts  = token["contacts"] != null ? token["contacts"] as JArray : null;

                                    if (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName))
                                    {
                                        person = provider.Create(firstName, lastName);
                                        if (person != null)
                                        {
                                            var result = true;
                                            if (contacts != null)
                                            {
                                                //add all contacts to person object
                                                foreach (JToken contact in contacts)
                                                {
                                                    string name  = contact["name"].ToString();
                                                    string email = contact["email"].ToString();
                                                    person.Contacts.Add(name, new EmailAddress(email));
                                                }

                                                //persist contact info
                                                result &= provider.Update(person);
                                            }

                                            if (result)
                                            {
                                                jperson = Jsonifier.ToJson(person);
                                                if (person != null)
                                                {
                                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok, jperson.ToString()));
                                                }
                                                else
                                                {
                                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                                }
                                                return;
                                            }
                                        }
                                    }
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                }
                                catch
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                            }
                            else if (meth.Equals("update", StringComparison.OrdinalIgnoreCase))
                            {
                                try
                                {
                                    JToken         token    = JsonUtils.GetDataPayload(context.Request);
                                    PersonProvider provider = PersonManager.Instance.GetProvider(ctx);
                                    Person         person   = null;
                                    bool           result   = true;

                                    CompoundIdentity id        = JsonUtils.ToId(token["id"]);
                                    string           firstName = token["firstname"].ToString();
                                    string           lastName  = token["lastname"].ToString();
                                    if (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName) && id != null)
                                    {
                                        person = new Person(id, firstName, lastName);

                                        if (token.SelectToken("contacts") != null && person != null)
                                        {
                                            JToken contact = token["contacts"];
                                            string name    = contact["name"].ToString();
                                            string email   = contact["schemeid"].ToString();
                                            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(email))
                                            {
                                                person.Contacts.Add(name, new EmailAddress(email));
                                            }
                                        }

                                        result &= provider.Update(person);
                                    }

                                    if (person != null && result)
                                    {
                                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok));
                                    }
                                    else
                                    {
                                        RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    }
                                    return;
                                }
                                catch
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                            }
                            else if (meth.Equals("delete", StringComparison.OrdinalIgnoreCase))
                            {
                                try
                                {
                                    bool           result   = true;
                                    JToken         token    = JsonUtils.GetDataPayload(context.Request);
                                    PersonProvider provider = PersonManager.Instance.GetProvider(ctx);
                                    if (provider != null && token != null)
                                    {
                                        string           first = token["firstname"].ToString();
                                        string           last  = token["lastname"].ToString();
                                        CompoundIdentity id    = JsonUtils.ToId(token["id"]);
                                        if (first != null && last != null && id != null)
                                        {
                                            Person p = new Person(id, first, last);
                                            result &= provider.Delete(p);
                                        }

                                        if (result == true)
                                        {
                                            RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok));
                                        }
                                        else
                                        {
                                            RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                        }
                                    }
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                }
                                catch
                                {
                                    RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                                    return;
                                }
                            }
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
                    return;
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #19
0
 public bool CanUpdate(UserIdentityBase identity)
 {
     return(this.CanUpdate());
 }
Beispiel #20
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl + "/", localUrl);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        try
                        {
                            if (meth.StartsWith(Get, StringComparison.OrdinalIgnoreCase))
                            {
                                try
                                {
                                    EntityBundleProvider prov = EntityBundleManager.Instance.GetProvider(ctx);
                                    if (prov != null)
                                    {
                                        JArray jbundles = Jsonifier.ToJson(prov.Get());
                                        if (jbundles != null)
                                        {
                                            RestUtils.Push(context.Response, JsonOpStatus.Ok, jbundles.ToString());
                                            return;
                                        }
                                        else
                                        {
                                            RestUtils.Push(context.Response, JsonOpStatus.Ok, "[]");
                                            return;
                                        }
                                    }

                                    RestUtils.Push(context.Response, JsonOpStatus.Failed);
                                }
                                catch
                                {
                                    RestUtils.Push(context.Response, JsonOpStatus.Failed);
                                    return;
                                }
                            }
                            else if (meth.StartsWith(In, StringComparison.OrdinalIgnoreCase))
                            {
                                //just need a bundle id to get  {id:<id>}
                                JToken token = JsonUtils.GetDataPayload(context.Request);
                                if (token != null)
                                {
                                    JObject o = token as JObject;
                                    if (o != null)
                                    {
                                        if (o[JsonUtils.Id] != null)
                                        {
                                            //Guid id = JsonUtils.ToGuid(token[JsonUtils.Id]);
                                            Guid id = JsonUtils.ToGuid(o[JsonUtils.Id] as JToken);
                                            if (!Guid.Empty.Equals(id))
                                            {
                                                EntityBundleProvider prov   = EntityBundleManager.Instance.GetProvider(ctx);
                                                EntityBundle         bundle = prov.Get(id);
                                                if (bundle != null)
                                                {
                                                    RestUtils.Push(context.Response, JsonOpStatus.Ok, Jsonifier.ToJson(bundle));
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else if (meth.StartsWith(Create, StringComparison.OrdinalIgnoreCase))
                            {
                                JToken token = JsonUtils.GetDataPayload(context.Request);
                                if (token != null)
                                {
                                    if (token[JsonUtils.Name] != null && token[JsonUtils.OwnerId] != null && token[Jsonifier.Type] != null && token[Jsonifier.Items] != null)
                                    {
                                        string name = token[JsonUtils.Name].ToString();
                                        if (!string.IsNullOrEmpty(name))
                                        {
                                            string type = token[Jsonifier.Type].ToString();
                                            if (!string.IsNullOrEmpty(type))
                                            {
                                                BundleDataType datType;
                                                if (type.StartsWith("site", StringComparison.OrdinalIgnoreCase))
                                                {
                                                    datType = BundleDataType.Site;
                                                }
                                                else if (type.StartsWith("taxa", StringComparison.OrdinalIgnoreCase))
                                                {
                                                    datType = BundleDataType.TaxaUnit;
                                                }
                                                else if (type.StartsWith("inst", StringComparison.OrdinalIgnoreCase))
                                                {
                                                    datType = BundleDataType.Instrument;
                                                }
                                                else
                                                {
                                                    context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
                                                    return;
                                                }
                                                CompoundIdentity cid = JsonUtils.ToId(token[JsonUtils.OwnerId]);
                                                if (cid != null && !cid.IsEmpty)
                                                {
                                                    JArray itemsArr = Items.GetItems(token[Jsonifier.Items]);
                                                    if (itemsArr != null && itemsArr.Count > 0)
                                                    {
                                                        List <Tuple <CompoundIdentity, string, string> > items = new List <Tuple <CompoundIdentity, string, string> >();
                                                        foreach (JToken cur in itemsArr)
                                                        {
                                                            Tuple <CompoundIdentity, string, string> tpl = Items.GetItem(cur);
                                                            if (tpl != null)
                                                            {
                                                                items.Add(tpl);
                                                            }
                                                        }

                                                        if (items.Count == itemsArr.Count)
                                                        {
                                                            if (Items.VandV(items, datType, ctx))
                                                            {
                                                                EntityBundleProvider prov   = EntityBundleManager.Instance.GetProvider(ctx);
                                                                EntityBundle         bundle = prov.Create(name, cid, datType);
                                                                if (bundle != null)
                                                                {
                                                                    foreach (Tuple <CompoundIdentity, string, string> tpl in items)
                                                                    {
                                                                        if (bundle.Add(tpl.Item1, tpl.Item2, tpl.Item3) == null)
                                                                        {
                                                                            RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"failed to add item to bundle\"");
                                                                            return;
                                                                        }
                                                                    }

                                                                    if (prov.Update(bundle))
                                                                    {
                                                                        RestUtils.Push(context.Response, JsonOpStatus.Ok, Jsonifier.ToJson(bundle));
                                                                        return;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else if (meth.StartsWith(Update, StringComparison.OrdinalIgnoreCase)) //note, this will just append items to the existing bundle and update bundle display name
                            {
                                //needs to have same content as create mostly -- doesn't require orgid (we ignore that since it can't change), and name is optional
                                JToken token = JsonUtils.GetDataPayload(context.Request);
                                if (token != null)
                                {
                                    if (token[JsonUtils.Id] != null && token[Jsonifier.Items] != null)
                                    {
                                        string name = null;
                                        if (token[JsonUtils.Name] != null)
                                        {
                                            name = token[JsonUtils.Name].ToString();
                                        }

                                        Guid id = JsonUtils.ToGuid(token[JsonUtils.Id]);
                                        if (!Guid.Empty.Equals(id))
                                        {
                                            JArray itemsArr = Items.GetItems(token[Jsonifier.Items]);
                                            if (itemsArr != null && itemsArr.Count > 0)
                                            {
                                                List <Tuple <CompoundIdentity, string, string> > items = new List <Tuple <CompoundIdentity, string, string> >();
                                                foreach (JToken cur in itemsArr)
                                                {
                                                    Tuple <CompoundIdentity, string, string> tpl = Items.GetItem(cur);
                                                    if (tpl != null)
                                                    {
                                                        items.Add(tpl);
                                                    }
                                                }

                                                if (items.Count == itemsArr.Count)
                                                {
                                                    token    = null;
                                                    itemsArr = null;

                                                    EntityBundleProvider prov   = EntityBundleManager.Instance.GetProvider(ctx);
                                                    EntityBundle         bundle = prov.Get(id);
                                                    if (bundle != null)
                                                    {
                                                        if (!string.IsNullOrEmpty(name) && !bundle.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                                                        {
                                                            bundle.Name = name;
                                                        }

                                                        //now we can actually try to add the items as needed
                                                        foreach (Tuple <CompoundIdentity, string, string> tpl in items)
                                                        {
                                                            if (!bundle.Contains(tpl.Item2))
                                                            {
                                                                if (bundle.Add(tpl.Item1, tpl.Item2, tpl.Item3) == null)
                                                                {
                                                                    RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"Failed to update bundle\"");
                                                                    return;
                                                                }
                                                            }
                                                        }

                                                        if (prov.Update(bundle))
                                                        {
                                                            RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok));
                                                            return;
                                                        }
                                                        else
                                                        {
                                                            RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"Failed to update bundle\"");
                                                            return;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        {
                            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
                            return;
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
                    return;
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #21
0
        public override void Handle(HttpContext context, CancellationToken cancel)
        {
            if (context != null)
            {
                UserIdentityBase user = Security.Session.GetUser(context);
                if (user != null)
                {
                    UserSecurityContext ctx = new UserSecurityContext(user);
                    string localUrl         = RestUtils.LocalUrl(this, context.Request);
                    string meth             = RestUtils.StripLocal(this.BaseUrl, localUrl);

                    if (!string.IsNullOrEmpty(meth))
                    {
                        if (meth.StartsWith(Upload, StringComparison.OrdinalIgnoreCase))
                        {
                            string err = null;
                            try
                            {
                                string fName = MetaInfo.GetFileName(context);             //TODO -- add origin filename handling
                                if (fName != null && MetaInfo.SupportedUploadType(fName)) //this might be a bogus way to go
                                {
                                    if (prov == null)
                                    {
                                        prov = FileStoreManager.Instance.GetProvider();
                                    }

                                    if (prov != null)
                                    {
                                        Stream input = context.Request.Body;
                                        if (input != null)
                                        {
                                            FilestoreFile fil = prov.MakeTemp();
                                            if (fil != null)
                                            {
                                                input.CopyTo(fil);
                                                fil.Flush();
                                                fil.Close();
                                                fil.FileName = fName;
                                                prov.Update(fil);
                                                RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Ok, "\"" + fil.FileId.ToString() + "\""));
                                                return;
                                            }
                                            else
                                            {
                                                err = "failed to make";
                                            }
                                        }
                                        else
                                        {
                                            err = "no file received";
                                        }
                                    }
                                    else
                                    {
                                        err = "no provider";
                                    }
                                }
                                else
                                {
                                    err = "unsupported file extension";  //this might be a bogus way to go
                                }
                            }
                            catch
                            { err = "unknown error"; }

                            if (err == null)
                            {
                                RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                            }
                            else
                            {
                                RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed, "\"" + err + "\""));
                            }
                            return;
                        }
                        if (meth.StartsWith(Download, StringComparison.OrdinalIgnoreCase))
                        {
                            string err = null;
                            try
                            {
                                //this should be a Guid string
                                string filename = Uri.UnescapeDataString(meth.Substring(Download.Length));
                                Guid   fileId;

                                if (Guid.TryParse(filename, out fileId))
                                {
                                    if (prov == null)
                                    {
                                        prov = FileStoreManager.Instance.GetProvider();
                                    }

                                    if (prov != null)
                                    {
                                        FilestoreFile fil = prov.Get(fileId);
                                        if (fil != null)
                                        {
                                            if (fil.Length > -1)
                                            {
                                                //send the bytes of a file in the response body
                                                context.Response.Headers.Add("Content-Disposition", "attachment ; filename=\"" + fil.FileName + "\"");
                                                context.Response.StatusCode  = HttpStatusCodes.Status200OK;
                                                context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                                                fil.CopyTo(context.Response.Body);
                                                return;
                                            }
                                            else
                                            {
                                                err = "no stream";
                                            }
                                        }
                                        else
                                        {
                                            err = "no such file";
                                        }
                                    }
                                    else
                                    {
                                        err = "no provider";
                                    }
                                }
                                else
                                {
                                    err = "fileid is not legal";
                                }
                            }
                            catch
                            { err = "unknown error"; }

                            if (err == null)
                            {
                                RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed));
                            }
                            else
                            {
                                RestUtils.Push(context.Response, RestUtils.JsonOpStatus(JsonOpStatus.Failed, "\"" + err + "\""));
                            }
                            return;
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = HttpStatusCodes.Status401Unauthorized;
                    return;
                }
            }
            context.Response.StatusCode = HttpStatusCodes.Status400BadRequest;
        }
Beispiel #22
0
        private void SignUp(HttpContext context, CancellationToken cancel)
        {
            string url = this.ActivateUrl;

            if (!string.IsNullOrEmpty(url))
            {
                IQueryCollection qry = context.Request.Query;
                string           ty  = qry[type];
                if (knownType.Equals(ty))
                {
                    string u = qry[user];
                    if (!string.IsNullOrEmpty(u))
                    {
                        string p = qry[pass];
                        if (!string.IsNullOrEmpty(p))
                        {
                            if (ValidUserEmail(u))
                            {
                                IIdentityProvider idProv = IdentityManager.Instance.GetProvider(ctx);
                                if (!idProv.Exists(u))
                                {
                                    IAuthenticationProvider authProv = AuthenticationManager.Instance.GetProvider(ctx);
                                    UserIdentityBase        user     = idProv.CreateUser(u);
                                    user.UserState = UserState.Pending;
                                    idProv.Update(user);
                                    UserPasswordCredential cred = new UserPasswordCredential(u, p);
                                    if (authProv.AddCredential(user, cred))
                                    {
                                        Guid token = Authenticator.Instance.Reset(u, false); //create a reset token
                                        //notice we create a url with the token at the end, this COULD map to the REST api directly - but is expected instead not to
                                        //we instead expect this to be a simple page that makes the rest request and "looks pretty" to confirm and perhaps send the user then back to the signin page.
                                        if (url.EndsWith("?"))
                                        {
                                            url = url + token.ToString();
                                        }
                                        else
                                        {
                                            url = url + "?" + token.ToString();
                                        }

                                        if (SendEmail(u, url, false))
                                        {
                                            RestUtils.Push(context.Response, JsonOpStatus.Ok);
                                            return;
                                        }
                                        else
                                        {
                                            idProv.Delete(user.Uid);
                                            authProv.DeleteCredential(user, cred);
                                            RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"Couldn't send email\"");
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        idProv.Delete(user.Uid);
                                        authProv.DeleteCredential(user, cred);
                                        RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"Couldn't set credential\"");
                                        return;
                                    }
                                }
                                else
                                {
                                    RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"UserExists\"");
                                    return;
                                }
                            }
                            else
                            {
                                RestUtils.Push(context.Response, JsonOpStatus.Failed, "\"InvalidEmail\"");
                                return;
                            }
                        }
                    }
                }
            }
            RestUtils.Push(context.Response, JsonOpStatus.Failed);
        }
Beispiel #23
0
        static void DoWork(string[] args)
        {
            AuthenticationManager.Instance.Bootstrap();
            Console.WriteLine("Authent state: " + AuthenticationManager.Instance.State);
            if (AuthenticationManager.Instance.State != Osrs.Runtime.RunState.Bootstrapped)
            {
                return;
            }

            AuthenticationManager.Instance.Initialize();
            Console.WriteLine("Authent state: " + AuthenticationManager.Instance.State);
            if (AuthenticationManager.Instance.State != Osrs.Runtime.RunState.Initialized)
            {
                return;
            }

            AuthenticationManager.Instance.Start();
            Console.WriteLine("Authent state: " + AuthenticationManager.Instance.State);
            if (AuthenticationManager.Instance.State != Osrs.Runtime.RunState.Running)
            {
                return;
            }

            LocalSystemUser     u   = new LocalSystemUser(SecurityUtils.AdminIdentity, "Admin", UserState.Active);
            UserSecurityContext ctx = new UserSecurityContext(u);

            string            myUname = "*****@*****.**";
            IIdentityProvider accts   = IdentityManager.Instance.GetProvider(ctx);
            UserIdentityBase  user    = null;

            if (!accts.Exists(myUname))
            {
                Console.WriteLine("Creating user account");
                user = accts.CreateUser(myUname);
            }
            else
            {
                Console.WriteLine("Fetching user account");
                IEnumerable <UserIdentityBase> users = accts.Get(myUname, UserType.Person);
                if (users != null)
                {
                    foreach (UserIdentityBase cur in users)
                    {
                        user = cur;
                        break;
                    }
                }
            }

            if (user == null)
            {
                Console.WriteLine("Failed to get/create user");
                return;
            }


            IAuthenticationProvider provider = AuthenticationManager.Instance.GetProvider(ctx);
            UserPasswordCredential  cred     = new UserPasswordCredential(myUname, "Hello World");
            IUserIdentity           u2       = provider.Authenticate(cred);

            if (u2 == null)
            {
                Console.WriteLine("Didn't authenticate -- adding credential");
                if (!provider.AddCredential(user, cred))
                {
                    Console.WriteLine("Failed to add credential");
                    return;
                }

                u2 = provider.Authenticate(cred);
                if (u2 == null)
                {
                    Console.WriteLine("Didn't authenticate -- giving up");
                    return;
                }
                else
                {
                    Console.WriteLine("Authenticated second try");
                }
            }
            else
            {
                Console.WriteLine("Authenticated first try");
            }

            Console.WriteLine("Replacing credential with same (should fail)");
            if (provider.ReplaceCredential(u2, cred, cred))
            {
                Console.WriteLine("Replace credential succeeded -- a failing result");
                return;
            }
            else
            {
                Console.WriteLine("Replace credential failed -- a successful result");
            }

            UserPasswordCredential cred2 = new UserPasswordCredential(myUname, "Alabaster Barkers 123");

            Console.WriteLine("Replacing credential with different (should succeed)");
            if (provider.ReplaceCredential(u2, cred, cred2))
            {
                Console.WriteLine("Replace credential succeeded -- a successful result");
            }
            else
            {
                Console.WriteLine("Replace credential failed -- a failing result");
                return;
            }

            u2 = provider.Authenticate(cred);
            if (u2 == null)
            {
                Console.WriteLine("Didn't authenticate with old credential -- successful");
                u2 = provider.Authenticate(cred2);
                if (u2 != null)
                {
                    Console.WriteLine("Authenticated with new credential -- successful");
                    return;
                }
            }
            Console.WriteLine("Password change didn't work out");
        }