Пример #1
0
Файл: dao.go Проект: itpkg/base
func (p *AuthDao) getRole(db *gorm.DB, name string, resource_type string, resource_id uint) *Role {
	role := Role{}
	db.FirstOrCreate(&role, Role{Name: name, ResourceType: resource_type, ResourceID: resource_id})

	db.Model(&role).Related(&role.Permissions)
	return &role
}
Пример #2
0
func tailLog(db gorm.DB, eventSample *stripe.Event) error {
	// Start paging from after the event sample that we capture before we
	// started loading from snapshot.
	params := &stripe.EventListParams{}
	params.Filters.AddFilter("limit", "", strconv.Itoa(PageSize))
	params.Filters.AddFilter("starting_after", "", eventSample.ID)

	var apiDuration, dbDuration time.Duration
	numProcessed := 0
	totalStart := time.Now()

	iterator := event.List(params)
	timeIterator := func() bool {
		start := time.Now()
		ret := iterator.Next()
		apiDuration = apiDuration + time.Now().Sub(start)
		return ret
	}

	for timeIterator() {
		start := time.Now()
		event := iterator.Event()

		switch event.Type {
		case "charge.created":
			charge := Charge{
				// TODO: deserialize to proper charge object
				ID:      event.Data.Obj["id"].(string),
				Amount:  event.Data.Obj["amount"].(uint64),
				Created: time.Unix(event.Data.Obj["created"].(int64), 0),
			}
			db.FirstOrCreate(&charge)
			dbDuration = dbDuration + time.Now().Sub(start)
			if db.Error != nil {
				return db.Error
			}

			numProcessed = numProcessed + 1
			if numProcessed%ReportingIncrement == 0 {
				log.Printf("Working. Processed %v record(s).", ReportingIncrement)
			}
		}
	}
	if err := iterator.Err(); err != nil {
		return err
	}

	log.Printf("")
	log.Printf("== Log Tailing Results")
	log.Printf("API duration:            %v", apiDuration)
	log.Printf("DB duration:             %v", dbDuration)
	log.Printf("Total duration:          %v", time.Now().Sub(totalStart))
	log.Printf("Total records processed: %v", numProcessed)
	return nil
}
Пример #3
0
func loadSnapshot(db gorm.DB) error {
	params := &stripe.ChargeListParams{}
	params.Filters.AddFilter("limit", "", strconv.Itoa(PageSize))

	var apiDuration, dbDuration time.Duration
	numProcessed := 0
	totalStart := time.Now()

	iterator := charge.List(params)
	timeIterator := func() bool {
		start := time.Now()
		ret := iterator.Next()
		apiDuration = apiDuration + time.Now().Sub(start)
		return ret
	}

	for timeIterator() {
		start := time.Now()
		charge := convertCharge(iterator.Charge())
		db.FirstOrCreate(&charge)
		dbDuration = dbDuration + time.Now().Sub(start)

		if db.Error != nil {
			return db.Error
		}

		numProcessed = numProcessed + 1
		if numProcessed%ReportingIncrement == 0 {
			log.Printf("Working. Processed %v record(s).", ReportingIncrement)
		}
	}
	if err := iterator.Err(); err != nil {
		return err
	}

	log.Printf("")
	log.Printf("== Snapshot Loading Results")
	log.Printf("API duration:            %v", apiDuration)
	log.Printf("DB duration:             %v", dbDuration)
	log.Printf("Total duration:          %v", time.Now().Sub(totalStart))
	log.Printf("Total records processed: %v", numProcessed)
	return nil
}
Пример #4
0
func getTumblrBlog(name string, db *gorm.DB) *TumblrBlog {
	blog := new(TumblrBlog)
	db.FirstOrCreate(blog, TumblrBlog{Name: name})
	return blog
}
Пример #5
0
// EnsureRepository inserts a Repository into the database if it doesn't exist and returns that Repository
func EnsureRepository(db *gorm.DB, given Repository) (repo Repository) {
	db.FirstOrCreate(&repo, given)
	return
}
Пример #6
0
func ListenAndServe(addr string, auth Auth, dbType DatabaseType) {
	var db *gorm.DB
	var err error

	if dbType == DB_MySQL {
		dbConn := fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)", auth.UserName, auth.Password)
		db, err = gorm.Open("mysql", dbConn+"/hugocms_"+auth.UserName+"?charset=utf8&parseTime=True&loc=Local")
	} else {
		db, err = gorm.Open("sqlite3", "hugocms_"+auth.UserName+".db")
	}

	if err != nil {
		handleError(err)
	}
	db.LogMode(true)

	// to reset to an empty database drop the settings table
	if !db.HasTable(&models.Settings{}) {
		for _, table := range hugocms_qor.Tables {
			if err := db.DropTableIfExists(table).Error; err != nil {
				handleError(err)
			}
		}
	}

	for _, table := range hugocms_qor.Tables {
		if err := db.AutoMigrate(table).Error; err != nil {
			handleError(err)
		}
	}

	// Because this is a singleton a single record must already exist in the database (there is no create through QOR admin just update)
	db.FirstOrCreate(&models.Settings{})

	siteName := fmt.Sprintf("%s - Hugo CMS", auth.UserName)
	if err := setupConfig(addr, siteName, db, auth); err != nil {
		handleError(err)
	}

	// Add session support - used by Auth
	sessionLifetime := 3600 // session lifetime in seconds
	SessionManager, err = session.NewManager("memory", fmt.Sprintf(`{"cookieName":"gosessionid","gclifetime":%d}`, sessionLifetime))
	if err != nil {
		handleError(err)
	}
	go SessionManager.GC()

	// Create Hugo's content directory if it doesnt exist
	// TODO read content dir from config
	if _, err := os.Stat("./content"); os.IsNotExist(err) {
		err = os.MkdirAll("./content", os.ModePerm)
	}

	mux := http.NewServeMux()

	mux.Handle("/", http.FileServer(http.Dir("public")))

	adm := hugocms_qor.SetupAdmin()

	adm.MountTo("/admin", mux)
	adm.GetRouter().Post("/auth", func(ctx *admin.Context) {
		// we will only hit this on succesful login - redirect to admin dashboard
		w := ctx.Writer
		r := ctx.Request
		http.Redirect(w, r, "/admin", http.StatusFound)
	})
	adm.GetRouter().Get("/logout", func(ctx *admin.Context) {
		w := ctx.Writer
		r := ctx.Request
		sess, err := SessionManager.SessionStart(w, r)
		if err != nil {
			handleError(err)
		}
		defer sess.SessionRelease(w)
		sess.Delete("User")
		http.Redirect(w, r, "/login", http.StatusFound)
	})

	// NOTE: `system` is where QOR admin will upload files e.g. images - we map this to Hugo's static dir along with our other static assets
	// TODO read static dir from config
	// TODO read static assets list from config
	for _, path := range []string{"system", "css", "fonts", "images", "js", "login"} {
		mux.Handle(fmt.Sprintf("/%s/", path), http.FileServer(http.Dir("static")))
	}

	if err := http.ListenAndServe(config.QOR.Addr, mux); err != nil {
		handleError(err)
	}

	// to re-generate site delete `config.json`
	if _, err := os.Stat("config.json"); os.IsNotExist(err) {
		hugocms_qor.CallSave(adm)
	}

	fmt.Printf("Listening on: %s\n", config.QOR.Addr)
}
Пример #7
0
func (s *Subscriber) Create(db *gorm.DB) error {
	return db.FirstOrCreate(s).Error
}
Пример #8
-1
func FillSrcInfo(path string, db *gorm.DB) error {
	f, err := os.Open(path)
	if err != nil {
		return err
	}
	defer f.Close()
	info, err := srcinfo.ParseSrcInfo(f)
	if err != nil {
		return err
	}
	var oldPkgBase PackageBase
	db.Select("id").First(&oldPkgBase, "pkg_base = ?", info.Global.PkgBase)
	pkgBase := PackageBase{
		ID:          oldPkgBase.ID,
		PkgBase:     info.Global.PkgBase,
		Packages:    []Package{},
		Version:     info.Global.PkgVer,
		Release:     info.Global.PkgRel,
		Depenencies: []Package{},
		Directory:   filepath.Dir(path),
	}
	log.Printf("  {%s}", pkgBase.PkgBase)
	depend := func(dependency string) {
		pkgName := StripDependencyPkgName(dependency)
		log.Printf("    %s => %s", dependency, pkgName)
		var dep Package
		db.FirstOrCreate(&dep, Package{Name: pkgName})
		log.Printf("    %+v", dep)
		pkgBase.Depenencies = append(pkgBase.Depenencies, dep)
	}
	for _, dependency := range info.Global.Depends {
		depend(dependency)
	}
	for _, dependency := range info.Global.MakeDepends {
		depend(dependency)
	}
	for _, pkginfo := range info.Packages {
		for _, dependency := range pkginfo.Depends {
			depend(dependency)
		}
		var pkg Package
		db.FirstOrCreate(&pkg, Package{
			PackageBaseID: pkgBase.ID,
			Name:          pkginfo.PkgName,
		})
		log.Printf("  %s", pkginfo.PkgName)
		pkgBase.Packages = append(pkgBase.Packages, pkg)
	}
	db.Save(&pkgBase)
	return nil
}