示例#1
0
        public IActionResult RegistrationStatus([FromRoute] string eventId, [FromHeader(Name = "Authorization")] string userToken)
        {
            ObjectId userId = new ObjectId(JwtUtil.GetUserIdFromToken(userToken));
            String   status = MongoUtil.GetRegistrationStatus(new ObjectId(eventId), userId);

            return(Ok(status));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SecurityTestBase{T}"/> class.
        /// </summary>
        /// <param name="testFixture">The application test fixture.</param>
        protected SecurityTestBase(AppTestFixture <Startup> testFixture)
            : base(testFixture)
        {
            Environment.SetEnvironmentVariable("GOOGLE_CLIENT_ID", this.Faker.Random.AlphaNumeric(10));
            Environment.SetEnvironmentVariable("GOOGLE_SECRET", this.Faker.Random.AlphaNumeric(10));
            Environment.SetEnvironmentVariable("FACEBOOK_CLIENT_ID", this.Faker.Random.AlphaNumeric(10));
            Environment.SetEnvironmentVariable("FACEBOOK_SECRET", this.Faker.Random.AlphaNumeric(10));

            testFixture?.ConfigureTestServices(services =>
            {
                // Setup user manager and role manager for integration test overriding the default implementation.
                var databaseOptions = new MongoIdentityOptions
                {
                    ConnectionString = testFixture.RepositoryConfiguration.ConnectionString
                };

                var userCollection = MongoUtil.FromConnectionString <UserAccount>(databaseOptions.ConnectionString, databaseOptions.UsersCollection);
                var roleCollection = MongoUtil.FromConnectionString <UserRole>(databaseOptions.ConnectionString, databaseOptions.RolesCollection);

                services.AddSingleton(x => userCollection);
                services.AddSingleton(x => roleCollection);

                services.AddTransient <IUserStore <UserAccount> >(x =>
                                                                  new UserStore <UserAccount, UserRole>(
                                                                      userCollection,
                                                                      new RoleStore <UserRole>(roleCollection),
                                                                      x.GetService <ILookupNormalizer>()));

                services.AddTransient <IRoleStore <UserRole> >(x => new RoleStore <UserRole>(roleCollection));
            });
        }
示例#3
0
        /// <summary>
        /// Note:  Before/After Save does not get called with this method.
        /// Find and Update FIRST matching document
        /// </summary>
        /// <param name="query"></param>
        /// <param name="sort"></param>
        /// <param name="update"></param>
        /// <param name="returnNew"></param>
        /// <param name="upsert"></param>
        /// <returns></returns>
        public FindAndModifyResult FindAndUpdate(IMongoQuery query, IMongoSortBy sort, IMongoUpdate update, bool returnNew, bool upsert)
        {
            //Implement necessary logic here (e.g.  auditing)
            IMongoQuery fixedQuery = MongoUtil.FormatIdElementForMongoQuery(query);

            return(Collection.FindAndModify(fixedQuery, sort, update, returnNew, upsert));
        }
示例#4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "WebTicket", Version = "v1"
                });
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer           = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ClockSkew        = TimeSpan.Zero,
                    ValidIssuer      = "WebTicket Server",
                    ValidAudience    = "WebTicket Client",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("JwtKey")))
                };
            });
            JwtUtil.setSecurityKey(Environment.GetEnvironmentVariable("JwtKey"));

            MongoUtil.InitializeConnection(Environment.GetEnvironmentVariable("MongoDBConnectionString"),
                                           Environment.GetEnvironmentVariable("MongoDBDatabaseName"));
        }
示例#5
0
 public IActionResult Browse([FromRoute] int pageSize, [FromRoute] int pageId)
 {
     return(Ok(MongoUtil.GetEvents(pageSize, pageId)
               .ConvertAll(new Converter <EventModel, EventApiModel>(eventModel => {
         return eventModel.getEventApiModel();
     }))));
 }
        public static IdentityBuilder AddIdentityMongoDbProvider <TUser, TRole>(this IServiceCollection services,
                                                                                Action <IdentityOptions> setupIdentityAction, Action <MongoIdentityOptions> setupDatabaseAction)
            where TUser : MongoUser
            where TRole : MongoRole
        {
            var dbOptions = new MongoIdentityOptions();

            setupDatabaseAction(dbOptions);

            var builder = services.AddIdentity <TUser, TRole>(setupIdentityAction ?? (x => { }));

            builder.AddRoleStore <RoleStore <TRole> >()
            .AddUserStore <UserStore <TUser, TRole> >()
            .AddUserManager <UserManager <TUser> >()
            .AddRoleManager <RoleManager <TRole> >()
            .AddDefaultTokenProviders();

            var userCollection = MongoUtil.FromConnectionString <TUser>(dbOptions.ConnectionString, dbOptions.UsersCollection);
            var roleCollection = MongoUtil.FromConnectionString <TRole>(dbOptions.ConnectionString, dbOptions.RolesCollection);

            services.AddSingleton(x => userCollection);
            services.AddSingleton(x => roleCollection);

            // Identity Services
            services.AddTransient <IRoleStore <TRole> >(x => new RoleStore <TRole>(roleCollection));
            services.AddTransient <IUserStore <TUser> >(x => new UserStore <TUser, TRole>(userCollection, new RoleStore <TRole>(roleCollection), x.GetService <ILookupNormalizer>()));

            return(builder);
        }
示例#7
0
        public IActionResult DeleteReview([FromRoute] String eventId, [FromHeader(Name = "Authorization")] String userToken)
        {
            MongoUtil.DeleteReview(new ObjectId(JwtUtil.GetUserIdFromToken(userToken)),
                                   new ObjectId(eventId));

            return(Ok());
        }
        public static IdentityBuilder AddIdentityMongoDbProvider <TUser, TRole>(this IServiceCollection services,
                                                                                Action <IdentityOptions> setupIdentityAction, Action <MongoIdentityOptions> setupDatabaseAction) where TUser : ApplicationUser
            where TRole : Role
        {
            MongoIdentityOptions dbOptions = new MongoIdentityOptions();

            setupDatabaseAction(dbOptions);

            IdentityBuilder builder = services.AddIdentity <TUser, TRole>(setupIdentityAction ?? (x => { }));

            builder.AddRoleStore <RoleStore <TRole> >()
            .AddUserStore <UserStore <TUser, TRole> >()
            .AddUserManager <UserManager <TUser> >()
            .AddRoleManager <RoleManager <TRole> >()
            .AddDefaultTokenProviders();

            IMongoCollection <TUser> userCollection = MongoUtil.FromConnectionString <TUser>(dbOptions.ConnectionString, dbOptions.DatabaseName, dbOptions.UsersCollection);
            IMongoCollection <TRole> roleCollection = MongoUtil.FromConnectionString <TRole>(dbOptions.ConnectionString, dbOptions.DatabaseName, dbOptions.RolesCollection);

            services.AddSingleton(x => userCollection);
            services.AddSingleton(x => roleCollection);

            // Identity Services
            services.AddTransient <IUserStore <TUser> >(x => new UserStore <TUser, TRole>(userCollection, roleCollection, x.GetService <ILookupNormalizer>()));
            services.AddTransient <IRoleStore <TRole> >(x => new RoleStore <TRole>(roleCollection));

            Task <System.Collections.Generic.List <TUser> > all = userCollection.All();

            all.Wait();

            return(builder);
        }
示例#9
0
        public IActionResult SendPasswordThroughEmail([FromRoute] string email)
        {
            UserModel user = MongoUtil.GetUser(email);

            if (user != null)
            {
                var smtpClient = new SmtpClient
                {
                    Host        = "smtp.gmail.com",
                    Port        = 587,
                    EnableSsl   = true,
                    Credentials = new NetworkCredential(Environment.GetEnvironmentVariable("SmtpUserName"), Environment.GetEnvironmentVariable("SmtpPassword"))
                };

                using (var message = new MailMessage(new MailAddress(Environment.GetEnvironmentVariable("SmtpUserName"), "WebTicket"), new MailAddress(user.Email))
                {
                    Subject = "Parolă cont",
                    Body = "Salut, " + user.Surname + " " + user.Name + ",\n\n" + Environment.NewLine + Environment.NewLine + "Parola contului tău este " + user.Password + Environment.NewLine + Environment.NewLine + "Nu răspunde acestei adrese de email. Este folosită doar pentru mesaje automate!"
                })
                {
                    smtpClient.Send(message);
                }

                return(Ok("Parola a fost trimisă pe email"));
            }

            return(Ok("Adresa de email introdusă nu se regăsește în baza de date!"));
        }
示例#10
0
        public IRepositoryMongo <T> Repository <T>(IMongoConfig mongoConfig) where T : class, IEntity
        {
            if (_repos.Count() == 0)
            {
                //build default tuple
                _repos.Add(new Tuple <IMongoConfig, SortedList <string, object> >(mongoConfig, new SortedList <string, object>()));
            }

            var repo = _repos.Where(x => x.Item1.ToString() == mongoConfig.ToString()).SingleOrDefault();

            if (repo == null)
            {
                _repos.Add(new Tuple <IMongoConfig, SortedList <string, object> >(mongoConfig, new SortedList <string, object>()));
                repo = _repos.Where(x => x.Item1.ToString() == mongoConfig.ToString()).SingleOrDefault();
            }


            if (!repo.Item2.ContainsKey(MongoUtil.GetCollectioNameFromInterface <T>()))
            {
                var config = repo.Item1;
                repo.Item2.Add(MongoUtil.GetCollectioNameFromInterface <T>(), new RepositoryMongo <T>(config));
            }

            return((IRepositoryMongo <T>)repo.Item2[MongoUtil.GetCollectioNameFromInterface <T>()]);
        }
示例#11
0
        /// <summary>
        /// Delete any auditing entries from AuditObjects collection.
        /// WARNING:  Source item MUST exist in order to delete from auditing using this method.
        /// To delete auditing history for a non-existant object, us the DeleteFromAuditing(DocumentAuditEnum, ID) overload.
        /// </summary>
        /// <param name="auditType"></param>
        /// <param name="criteria"></param>
        public void DeleteFromAuditing(DocumentAuditEnum auditType, Expression <Func <T, bool> > criteria)
        {
            string colName = MongoUtil.GetCollectioNameFromInterface <T>();

            if (colName == "AuditObjects")
            {
                throw new Exception(
                          "RepositoryMongo.DeleteFromAuditing cannot be used for audit objects themselves.  To delete an AuditOjbect, use the Delete method");
            }

            var audit = typeof(T).GetCustomAttributes(typeof(DocumentAuditAttr), false).SingleOrDefault();

            if (audit != null)
            {
                var sourceObjects = All(criteria);

                if (((audit as DocumentAuditAttr).AuditEnum & DocumentAuditEnum.Edit) == DocumentAuditEnum.Edit)
                {
                    foreach (var soureObject in sourceObjects)
                    {
                        Repositories.Instance.Repository <AuditObject>(_mongoConfig).Delete(x => x.Action == "UPD" && x.Source == colName && x.OriginalId == soureObject._id);
                    }
                }
                if (((audit as DocumentAuditAttr).AuditEnum & DocumentAuditEnum.Delete) == DocumentAuditEnum.Delete)
                {
                    //delete where action = "DEL";
                    foreach (var soureObject in sourceObjects)
                    {
                        Repositories.Instance.Repository <AuditObject>(_mongoConfig).Delete(x => x.Action == "DEL" && x.Source == colName && x.OriginalId == soureObject._id);
                    }
                }
            }
        }
示例#12
0
 public IActionResult Search([FromRoute] int pageSize, [FromRoute] int pageId, [FromRoute] String searchText)
 {
     return(Ok(MongoUtil.Search(pageSize, pageId, searchText)
               .ConvertAll(new Converter <EventModel, EventApiModel>(eventModel => {
         return eventModel.getEventApiModel();
     }))));
 }
示例#13
0
        /// <summary>
        /// If T is new, inserts into collection, otherwise REPLACE item in collection with T
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T Update(T entity)
        {
            OnBeforeSave(entity);

            var audit =
                typeof(T).GetCustomAttributes(typeof(DocumentAuditAttr), false).SingleOrDefault();

            if (audit != null && entity._id != null && ((audit as DocumentAuditAttr).AuditEnum & DocumentAuditEnum.Edit) == DocumentAuditEnum.Edit)
            {
                var editedObjRep = Repositories.Instance.Repository <AuditObject>(_mongoConfig);
                var auditObject  = new AuditObject();
                auditObject.OriginalId = entity._id;
                auditObject.Action     = "UPD";
                auditObject.Source     = MongoUtil.GetCollectioNameFromInterface <T>();

                T originalItem = FindOneById(entity._id);

                if (originalItem != null)
                {
                    auditObject.Item = originalItem.ToBsonDocument(typeof(T));
                    editedObjRep.Add(auditObject);
                }
            }

//            if (typeof(IAuditFields).IsAssignableFrom(typeof(T)))
//            {
//                AuditAddEdit(entity);
//            }

            Collection.Save <T>(entity);

            OnAfterSave(entity);

            return(entity);
        }
示例#14
0
        public WriteConcernResult Update(IMongoQuery query, UpdateBuilder update, UpdateFlags updateFlags, WriteConcern writeConcern)
        {
            //TODO:  paul, deal with auditing
            IMongoQuery fixedQuery = MongoUtil.FormatIdElementForMongoQuery(query);

            return(Collection.Update(query, update, updateFlags, writeConcern));
        }
示例#15
0
        public void Delete(T entity, bool saveCopyOfDeletedItem)
        {
            OnBeforeDelete(entity);

            //don't archive anything from the DeletedObjects collection.
            if (saveCopyOfDeletedItem && MongoUtil.GetCollectioNameFromInterface <T>() != "AuditObjects")
            {
                //                var audit =
                //                    typeof (T).GetCustomAttributes(typeof (DocumentAuditAttr), false).SingleOrDefault();

                //                if (audit != null && ((audit as DocumentAuditAttr).AuditEnum & DocumentAuditEnum.Delete )== DocumentAuditEnum.Delete)
                {
                    var deletedObjRepo = Repositories.Instance.Repository <AuditObject>(_mongoConfig);
                    var deletedObject  = new AuditObject();
                    deletedObject.OriginalId = entity._id;
                    deletedObject.Action     = "DEL";
                    deletedObject.Source     = MongoUtil.GetCollectioNameFromInterface <T>();
                    deletedObject.Item       = entity.ToBsonDocument(typeof(T));
                    deletedObjRepo.Add(deletedObject);
                }
            }

            //WriteConcernResult result;
            RemoveItemById(entity);

            OnAfterDelete(entity);
        }
 public AccountController()
 {
     _userManager =
         new ApplicationUserManager(
             new UserStore <IdentityUser>(MongoUtil <IdentityUser> .GetDefaultConnectionString()));
     _galleonUserStore = new GalleonUserStore(MongoUtil <GalleonRegistrationModel> .GetDefaultConnectionString());
 }
示例#17
0
        public IActionResult RegisterUserToEvent([FromRoute] string eventId, [FromHeader(Name = "Authorization")] string token)
        {
            ObjectId userId = new ObjectId(JwtUtil.GetUserIdFromToken(token));
            Boolean  ok     = MongoUtil.RegisterUserToEvent(new ObjectId(eventId), userId);

            return(Ok(ok));
        }
示例#18
0
        public IActionResult ChangePassword([FromBody] UserApiModel newPass, [FromHeader(Name = "Authorization")] string token)
        {
            ObjectId userId = new ObjectId(JwtUtil.GetUserIdFromToken(token));

            MongoUtil.ChangePassword(userId, newPass.Password);

            return(Ok());
        }
示例#19
0
        public Task blacklistAdd(params string[] words)
        {
            guildData d = MongoUtil.getGuildData(Context.Guild.Id);

            d.blacklistedWords.AddRange(words);
            MongoUtil.updateGuildData(d);
            return(Task.CompletedTask);
        }
示例#20
0
 public MailController()
 {
     _mail        = new MailStore <Mail>(MongoUtil <Mail> .GetDefaultConnectionString());
     _userManager =
         new ApplicationUserManager(
             new UserStore <IdentityUser>(MongoUtil <IdentityUser> .GetDefaultConnectionString()));
     _check = new CheckStore <CheckModel>(MongoUtil <Mail> .GetDefaultConnectionString());
 }
示例#21
0
        public MongoCursor <T> Find(IMongoQuery query, params string[] propertiesToReturn)
        {
            IMongoQuery fixedQuery = MongoUtil.FormatIdElementForMongoQuery(query);
            var         cursor     = Collection.Find(fixedQuery);

            cursor.SetFields(propertiesToReturn);

            return(cursor);
        }
示例#22
0
        public IActionResult Created([FromRoute] int pageSize, [FromRoute] int pageId, [FromHeader(Name = "Authorization")] string token)
        {
            ObjectId userId = new ObjectId(JwtUtil.GetUserIdFromToken(token));

            return(Ok(MongoUtil.GetCreatedEvents(userId, pageSize, pageId)
                      .ConvertAll(new Converter <EventModel, EventApiModel>(e => {
                return e.getEventApiModel();
            }))));
        }
示例#23
0
        public IEnumerable <string> Distinct(string key, IMongoQuery query)
        {
            IMongoQuery fixedQuery = MongoUtil.FormatIdElementForMongoQuery(query);

            var results = Collection.Distinct(key, fixedQuery);

            return(results.Where(x => x != BsonNull.Value)
                   .Select(x => x.ToString()));
        }
示例#24
0
 private Task UserLeft(SocketGuildUser user)
 {
     #region Leave message
     guildData   d = MongoUtil.getGuildData(user.Guild.Id);
     SocketGuild g = client.GetGuild(user.Guild.Id);
     g.SystemChannel.SendMessageAsync(d.joinMsg);
     #endregion
     return(Task.CompletedTask);
 }
示例#25
0
        public IQueryable <T> FindDeleted()
        {
            MongoCursor <AuditObject> allAuditObjs = Repositories.Instance.Repository <AuditObject>(_mongoConfig).FindAll();

            string colName = MongoUtil.GetCollectioNameFromInterface <T>();

            var asAuditObjs = allAuditObjs.Where(x => x.Source == colName && x.Action == "DEL").ToList();

            return(asAuditObjs.Select(item => item.Item).Select(doc => (T)BsonSerializer.Deserialize((BsonDocument)doc, typeof(T))).ToList().AsQueryable());
        }
示例#26
0
        public RepositoryMongo(IMongoConfig mongoConfig)
        {
            //MongoServer server = MongoServer.Create(mongoConfig.SettingsServer);
            var           cnn    = mongoConfig.MongoUrl;
            MongoServer   server = new MongoClient(cnn).GetServer();
            MongoDatabase db     = server.GetDatabase(mongoConfig.Database.Name);

            _mongoConfig = mongoConfig;
            _collection  = db.GetCollection <T>(MongoUtil.GetCollectioNameFromInterface <T>());
        }
示例#27
0
        public IActionResult Create([FromHeader(Name = "Authorization")] string token, [FromBody] EventApiModel eventApiModel)
        {
            String     userId     = JwtUtil.GetUserIdFromToken(token);
            EventModel eventModel = eventApiModel.getEventModel(userId, DateTime.Now);

            eventModel.Image = "StaticFiles/Images/standard.jpg";
            MongoUtil.AddEvent(eventModel);

            return(Ok("Event created"));
        }
示例#28
0
        public IActionResult Signup([FromBody] UserApiModel userApiModel)
        {
            if (MongoUtil.GetUser(userApiModel.getUserModel(ModelsExtensionMethods.zeroId).Email) == null)
            {
                MongoUtil.AddUser(userApiModel.getUserModel(ModelsExtensionMethods.zeroId));
                return(Ok("Success"));
            }

            return(Conflict("Email used"));
        }
示例#29
0
        public IActionResult EditReview([FromRoute] String eventId, [FromHeader(Name = "Authorization")] String userToken, [FromBody] ReviewApiModel reviewApiModel)
        {
            MongoUtil.EditReview(new ObjectId(JwtUtil.GetUserIdFromToken(userToken)),
                                 new ObjectId(eventId),
                                 reviewApiModel.Rating,
                                 reviewApiModel.Opinion,
                                 DateTime.Now);

            return(Ok());
        }
示例#30
0
        public Task setCmdPrefix(string p)
        {
            guildData d = MongoUtil.getGuildData(Context.Guild.Id);

            d.prefix = p;
            MongoUtil.updateGuildData(d);
            Context.Guild.CurrentUser.ModifyAsync(c => c.Nickname = $"OpenUtil ({p})");
            Context.Channel.SendMessageAsync($"Set prefix to {p}");
            return(Task.CompletedTask);
        }