Beispiel #1
0
func Logger(c *gin.Context) {
	requestId := util.NewId()
	c.Set("request_id", requestId)

	method := c.Request.Method
	path := c.Request.URL.EscapedPath()
	ip := c.ClientIP()

	log.InfoFields("Request received", log.Fields{
		"request_id": requestId,
		"method":     method,
		"ip":         ip,
		"path":       path,
	})

	start := time.Now()
	c.Next()
	duration := time.Since(start)

	code := c.Writer.Status()

	log.InfoFields("Request handled", log.Fields{
		"request_id": requestId,
		"took":       duration.String(),
		"code":       code,
	})

}
Beispiel #2
0
func SignInPost(c *gin.Context) {
	db := models.GetDB()
	session := sessions.Default(c)

	login := &models.Login{}
	if c.Bind(login) == nil {
		user := &models.User{}
		db.Where("lower(email) = lower(?)", login.Email).First(user)
		if user.ID == 0 {
			log.Printf("ERROR: Login failed, IP: %s, Email: %s\n", c.ClientIP(), login.Email)
			session.AddFlash("Эл. адрес или пароль указаны неверно")
			session.Save()
			c.Redirect(303, "/signin")
			return
		}
		//create user
		if err := user.ComparePassword(login.Password); err != nil {
			log.Printf("ERROR: Login failed, IP: %s, Email: %s\n", c.ClientIP(), login.Email)
			session.AddFlash("Эл. адрес или пароль указаны неверно")
			session.Save()
			c.Redirect(303, "/signin")
			return
		}

		session.Set("user_id", user.ID)
		session.Save()
		c.Redirect(303, "/")
	}
}
Beispiel #3
0
//SignInPost handles POST /signin route, authenticates user
func SignInPost(c *gin.Context) {
	session := sessions.Default(c)
	user := &models.User{}
	if err := c.Bind(user); err != nil {
		session.AddFlash("Please, fill out form correctly.")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}

	userDB, _ := models.GetUserByEmail(user.Email)
	if userDB.ID == 0 {
		logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
		session.AddFlash("Email or password incorrect")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}
	if err := bcrypt.CompareHashAndPassword([]byte(userDB.Password), []byte(user.Password)); err != nil {
		logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
		session.AddFlash("Email or password incorrect")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}

	session.Set("UserID", userDB.ID)
	session.Save()
	c.Redirect(http.StatusFound, "/")
}
Beispiel #4
0
func view(c *gin.Context) {
	id := c.Param("uniuri")
	key := c.Param("key")
	re := models.ResourceEntry{}
	remote := c.ClientIP()

	db.Where(&models.ResourceEntry{Key: id}).First(&re)
	if re.Key == "" {
		log.Printf("[INFO][%s]\tNot found : %s", remote, id)
		c.AbortWithStatus(http.StatusNotFound)
		return
	}
	log.Printf("[INFO][%s]\tFetched %s file and entry\n", remote, id)
	f, err := os.Open(path.Join(conf.C.UploadDir, re.Key))
	if err != nil {
		log.Printf("[ERROR][%s]\tWhile opening %s file\n", remote, id)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		log.Printf("[ERROR][%s]\tDuring Cipher creation : %s\n", remote, err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	var iv [aes.BlockSize]byte
	stream := cipher.NewCFBDecrypter(block, iv[:])
	reader := &cipher.StreamReader{S: stream, R: f}
	c.Header("Content-Disposition", "filename=\""+re.Name+"\"")
	io.Copy(c.Writer, reader)
}
Beispiel #5
0
func index(c *gin.Context) {
	log.Printf("[INFO][%s]\tIssued a GET request\n", c.ClientIP())
	if conf.C.FullDoc {
		c.HTML(http.StatusOK, "index.html", gin.H{})
	} else {
		c.HTML(http.StatusOK, "welcome.html", gin.H{})
	}
}
Beispiel #6
0
func putFile(c *gin.Context) {
	if isIPBanned(c.ClientIP()) {
		c.Data(200, "text/plain", []byte("You are rate limited to 20 requests/hour."))
		return
	}
	filename := c.Param("title")
	if len(filename) == 0 {
		filename = randomAlliterateCombo()
	}
	contentLength := c.Request.ContentLength
	var reader io.Reader
	reader = c.Request.Body
	if contentLength == -1 {
		// queue file to disk, because s3 needs content length
		var err error
		var f io.Reader

		f = reader

		var b bytes.Buffer

		n, err := io.CopyN(&b, f, _24K+1)
		if err != nil && err != io.EOF {
			log.Printf("%s", err.Error())
		}

		if n > _24K {
			file, err := ioutil.TempFile("./", "transfer-")
			if err != nil {
				log.Printf("%s", err.Error())
			}

			defer file.Close()

			n, err = io.Copy(file, io.MultiReader(&b, f))
			if err != nil {
				os.Remove(file.Name())
				log.Printf("%s", err.Error())
			}

			reader, err = os.Open(file.Name())
		} else {
			reader = bytes.NewReader(b.Bytes())
		}

		contentLength = n
	}
	buf := new(bytes.Buffer)
	buf.ReadFrom(reader)
	// p := WikiData{filename, "", []string{}, []string{}, false, ""}
	// p.save(buf.String())
	var p WikiData
	p.load(strings.ToLower(filename))
	p.save(buf.String())
	c.Data(200, "text/plain", []byte("File uploaded to http://"+RuntimeArgs.ExternalIP+"/"+filename))
}
Beispiel #7
0
// GetIP : just get the client ip
func GetIP(c *gin.Context) (ip net.IP, err error) {
	tmp := c.ClientIP()
	ipStr, _, err := net.SplitHostPort(tmp)
	ip = net.ParseIP(ipStr)
	if err != nil {
		logger.Error("Client IP fail , %s", err)
		return nil, err
	}
	return ip, nil
}
Beispiel #8
0
// PushBuildLogs pushes the updated build logs.
func PushBuildLogs(c *gin.Context) {
	var (
		owner  = c.Param("owner")
		name   = c.Param("name")
		number = c.Param("build")
		job    = c.Param("job")
	)
	io.Copy(c.Writer, c.Request.Body)

	log.Printf("Agent %s pushed logs for %s/%s#%s.%s", c.ClientIP(), owner, name, number, job)
}
Beispiel #9
0
func (m *Mongo) GetSubjects(c *gin.Context) {
	var subject []models.Subject

	log.Println(c.ClientIP())

	subject = new(models.Subject).Get(m.Database)
	c.JSON(http.StatusOK, gin.H{
		"err":      false,
		"subjects": subject,
	})
}
Beispiel #10
0
func (m *Mongo) GetTags(c *gin.Context) {
	var tag []models.Tags

	log.Println(c.ClientIP())

	tag = new(models.Tags).Get(m.Database)
	c.JSON(http.StatusOK, gin.H{
		"err":  false,
		"tags": tag,
	})
}
Beispiel #11
0
func create(c *gin.Context) {
	var err error
	remote := c.ClientIP()
	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, conf.C.LimitSize*1000000)

	fd, h, err := c.Request.FormFile("file")
	if err != nil {
		log.Printf("[ERROR][%s]\tDuring reading file : %s", remote, err)
		c.String(http.StatusRequestEntityTooLarge, "Entity is too large (Max : %v MB)\n", conf.C.LimitSize)
		c.AbortWithStatus(http.StatusRequestEntityTooLarge)
		return
	}
	defer fd.Close()

	u := uniuri.NewLen(conf.C.UniURILength)

	k := uniuri.NewLen(16)
	kb := []byte(k)
	block, err := aes.NewCipher(kb)
	if err != nil {
		log.Printf("[ERROR][%s]\tDuring Cipher creation : %s\n", remote, err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	var iv [aes.BlockSize]byte
	stream := cipher.NewCFBEncrypter(block, iv[:])

	path := path.Join(conf.C.UploadDir, u)
	file, err := os.Create(path)
	if err != nil {
		log.Printf("[ERROR][%s]\tDuring file creation : %s\n", remote, err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	defer file.Close()

	writer := &cipher.StreamWriter{S: stream, W: file}
	// No encryption : wr, err := io.Copy(file, bufio.NewReaderSize(fd, 512))
	// Copy the input file to the output file, encrypting as we go.
	wr, err := io.Copy(writer, bufio.NewReaderSize(fd, 512))
	if err != nil {
		log.Printf("[ERROR][%s]\tDuring writing : %s\n", remote, err)
		c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
		c.AbortWithStatus(http.StatusInternalServerError)
	}
	db.Create(&models.ResourceEntry{Key: u, Name: h.Filename})

	log.Printf("[INFO][%s]\tCreated %s file and entry (%v bytes written)\n", remote, u, wr)
	c.String(http.StatusCreated, "https://%s/v/%s/%s\n", conf.C.NameServer, u, k)
}
func rateLimit(c *gin.Context) {

	ip := c.ClientIP()
	value := int(ips.Add(ip, 1))
	if value%50 == 0 {
		fmt.Printf("ip: %s, count: %d\n", ip, value)
	}
	if value >= 200 {
		if value%200 == 0 {
			fmt.Println("ip blocked")
		}
		c.Abort()
		c.String(503, "you were automatically banned :)")
	}
}
Beispiel #13
0
// PushBuild pushes the updated build.
func PushBuild(c *gin.Context) {
	var (
		owner  = c.Param("owner")
		name   = c.Param("name")
		number = c.Param("build")
		job    = c.Param("job")
	)
	work := new(queue.Work)
	if err := c.BindJSON(work); err != nil {
		log.Printf("Invalid JSON input. %s", err)
		c.String(500, "Invalid JSON input. %s", err)
		return
	}
	c.JSON(200, work)

	log.Printf("Agent %s pushed update for %s/%s#%s.%s %s",
		c.ClientIP(), owner, name, number, job, work.Job.Status)
}
Beispiel #14
0
func apiLog(c *gin.Context) {
	start := time.Now()
	path := c.Request.URL.Path
	// before request
	c.Next()
	// after request

	end := time.Now()
	latency := end.Sub(start)

	status := c.Writer.Status()
	client := c.ClientIP()
	method := c.Request.Method

	log.Infof("%v %v %v %v %v",
		latency, client, method, path, status)

}
Beispiel #15
0
// Stream streams the logs to disk or memory for broadcasing to listeners. Once
// the stream is closed it is moved to permanent storage in the database.
func Stream(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.String(500, "Invalid input. %s", err)
		return
	}

	key := c.Param("id")
	logrus.Infof("Agent %s creating stream %s.", c.ClientIP(), key)

	wc, err := stream.Writer(c, key)
	if err != nil {
		c.String(500, "Failed to create stream writer. %s", err)
		return
	}

	defer func() {
		wc.Close()
		stream.Delete(c, key)
	}()

	io.Copy(wc, c.Request.Body)

	rc, err := stream.Reader(c, key)
	if err != nil {
		c.String(500, "Failed to create stream reader. %s", err)
		return
	}

	wg := sync.WaitGroup{}
	wg.Add(1)

	go func() {
		defer recover()
		store.WriteLog(c, &model.Job{ID: id}, rc)
		wg.Done()
	}()

	wc.Close()
	wg.Wait()
	c.String(200, "")

	logrus.Debugf("Agent %s wrote stream to database", c.ClientIP())
}
Beispiel #16
0
// Pull pulls work from the worker queue.
func Pull(c *gin.Context) {
	log.Printf("Agent %s connected and waiting for work.", c.ClientIP())

	w := queue.PullClose(c, c.Writer)
	if w == nil {
		c.String(500, "Connection Closed")
		return
	}

	c.JSON(200, w)

	log.Printf("Agent %s assigned work. %s/%s#%d.%d",
		c.ClientIP(),
		w.Repo.Owner,
		w.Repo.Name,
		w.Build.Number,
		w.Job.Number,
	)
}
Beispiel #17
0
// Poll polls for system events and broadcasts to all workers.
func Poll(c *gin.Context) {

	log.Printf("Agent %s opening websocket.", c.ClientIP())

	// upgrade the websocket
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Printf("Error upgrading connection. %s", err)
		c.String(500, "Error upgrading connection. %s", err)
		return
	}

	quitc := make(chan bool, 1)
	eventc := make(chan *bus.Event, 1)
	bus.Subscribe(c, eventc)

	defer func() {
		bus.Unsubscribe(c, eventc)

		ws.Close()
	}()

	defer ws.Close()

	go func() {
		for {
			select {
			case event := <-eventc:
				if event.Kind == bus.EventCancel ||
					event.Kind == bus.EventCleanup {
					ws.WriteJSON(event)
				}
			case <-quitc:
				return
			}
		}
	}()

	readWebsocket(ws)
	quitc <- true

	log.Printf("Agent %s closing websocket.", c.ClientIP())
}
Beispiel #18
0
//logger is the middleware to run with every request
//It will log all the request information like timestamp, clientIp, response code,
// response duration, method, path, protocol and response size
//It will also help to recover any sort panic, fatal etc
func logger(c *gin.Context) {
	var start time.Time
	const logFormat = "%s " + // Timestamp
		"%s " + // Client ip
		"%d " + // Response code
		"%v " + // Response Duration
		`"%s %s %s" ` + // Request method, path and protocol
		"%d " // Response size

	defer func() {
		const INTERNAL_SERVER_ERROR = 500
		if err := recover(); err != nil {
			duration := time.Now().Sub(start)
			log.Printf(logFormat+"\n%v\n%s",
				start.Format(timeFormat),
				c.ClientIP(),
				INTERNAL_SERVER_ERROR,
				duration,
				c.Request.Method,
				c.Request.URL.Path,
				c.Request.Proto,
				c.Writer.Size(),
				err,
				debug.Stack(),
			)
			c.AbortWithStatus(INTERNAL_SERVER_ERROR)
		}
	}()
	start = time.Now()
	c.Next()
	duration := time.Now().Sub(start)
	log.Printf(logFormat+"\n%s",
		start.Format(timeFormat),
		c.ClientIP(),
		c.Writer.Status(),
		duration,
		c.Request.Method,
		c.Request.URL.Path,
		c.Request.Proto,
		c.Writer.Size(),
		c.Errors.String(),
	)
}
Beispiel #19
0
func Ping(c *gin.Context) {
	agent, err := store.GetAgentAddr(c, c.ClientIP())
	if err == nil {
		agent.Updated = time.Now().Unix()
		err = store.UpdateAgent(c, agent)
	} else {
		err = store.CreateAgent(c, &model.Agent{
			Address:  c.ClientIP(),
			Platform: "linux/amd64",
			Capacity: 2,
			Created:  time.Now().Unix(),
			Updated:  time.Now().Unix(),
		})
	}
	if err != nil {
		logrus.Errorf("Unable to register agent. %s", err.Error())
	}
	c.String(200, "PONG")
}
Beispiel #20
0
func (self *Server) showPing(c *gin.Context) {
	u4, err := uuid.NewV4()
	if err != nil {
		self.Log.Error("Is not generate uuid", err.Error())
	}
	sesUuid := fmt.Sprintf("%v", u4)

	storeID, err := strconv.Atoi(c.Param("region_id"))
	if err != nil {
		self.Log.Error("Region ID is not integer", storeID)
	}

	t := time.Now().UTC()
	acceptLanguage := c.Request.Header.Get("Accept-Language")[0:2]
	go self.saveShow(t, sesUuid, storeID, c.Param("umac"), c.ClientIP(), acceptLanguage, c.Request.Referer(), c.Request.UserAgent())

	c.Header("cache-control", "priviate, max-age=0, no-cache")
	c.Header("pragma", "no-cache")
	c.Header("expires", "-1")
	c.Header("Last-Modified", fmt.Sprintf("%v", t))
	c.Header("Content-Type", "text/javascript")
	c.String(200, fmt.Sprintf("var uatv_me_uuid='%s',lang='%s';", sesUuid, acceptLanguage))
}
Beispiel #21
0
// Pull is a long request that polls and attemts to pull work off the queue stack.
func Pull(c *gin.Context) {
	logrus.Debugf("Agent %s connected.", c.ClientIP())

	w := queue.PullClose(c, c.Writer)
	if w == nil {
		logrus.Debugf("Agent %s could not pull work.", c.ClientIP())
	} else {
		c.JSON(202, w)

		logrus.Debugf("Agent %s assigned work. %s/%s#%d.%d",
			c.ClientIP(),
			w.Repo.Owner,
			w.Repo.Name,
			w.Build.Number,
			w.Job.Number,
		)
	}
}
Beispiel #22
0
// Pull is a long request that polls and attemts to pull work off the queue stack.
func Pull(c *gin.Context) {
	logrus.Debugf("Agent %s connected.", c.ClientIP())

	w := queue.PullClose(c, c.Writer)
	if w == nil {
		logrus.Debugf("Agent %s could not pull work.", c.ClientIP())
	} else {

		// setup the channel to stream logs
		if err := stream.Create(c, stream.ToKey(w.Job.ID)); err != nil {
			logrus.Errorf("Unable to create stream. %s", err)
		}

		c.JSON(202, w)

		logrus.Debugf("Agent %s assigned work. %s/%s#%d.%d",
			c.ClientIP(),
			w.Repo.Owner,
			w.Repo.Name,
			w.Build.Number,
			w.Job.Number,
		)
	}
}
Beispiel #23
0
// CloseThreadController will toggle a threads close bool
func CloseThreadController(c *gin.Context) {

	// Get parameters from validate middleware
	params := c.MustGet("params").([]uint)

	// get userdata from user middleware
	userdata := c.MustGet("userdata").(user.User)

	if !c.MustGet("protected").(bool) {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(e.ErrInternalError).SetMeta("CloseThreadController.protected")
		return
	}

	// Initialize model struct
	m := &models.CloseModel{
		Ib: params[0],
		ID: params[1],
	}

	// Check the record id and get further info
	err := m.Status()
	if err == e.ErrNotFound {
		c.JSON(e.ErrorMessage(e.ErrNotFound))
		c.Error(err).SetMeta("CloseThreadController.Status")
		return
	} else if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("CloseThreadController.Status")
		return
	}

	// toggle status
	err = m.Toggle()
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("CloseThreadController.Toggle")
		return
	}

	// Delete redis stuff
	indexKey := fmt.Sprintf("%s:%d", "index", m.Ib)
	directoryKey := fmt.Sprintf("%s:%d", "directory", m.Ib)
	threadKey := fmt.Sprintf("%s:%d:%d", "thread", m.Ib, m.ID)

	err = redis.Cache.Delete(indexKey, directoryKey, threadKey)
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("CloseThreadController.redis.Cache.Delete")
		return
	}

	var successMessage string

	// change response message depending on bool state
	if m.Closed {
		successMessage = audit.AuditOpenThread
	} else {
		successMessage = audit.AuditCloseThread
	}

	// response message
	c.JSON(http.StatusOK, gin.H{"success_message": successMessage})

	// audit log
	audit := audit.Audit{
		User:   userdata.ID,
		Ib:     m.Ib,
		Type:   audit.ModLog,
		IP:     c.ClientIP(),
		Action: successMessage,
		Info:   fmt.Sprintf("%s", m.Name),
	}

	// submit audit
	err = audit.Submit()
	if err != nil {
		c.Error(err).SetMeta("CloseThreadController.audit.Submit")
	}

	return

}
Beispiel #24
0
func resolveClientIP(context *gin.Context) net.IP {
	clientIp := strings.Split(context.ClientIP(), ":")[0]
	return net.ParseIP(clientIp)
}
Beispiel #25
0
// DeleteTagController will delete a tag
func DeleteTagController(c *gin.Context) {

	// Get parameters from validate middleware
	params := c.MustGet("params").([]uint)

	// get userdata from user middleware
	userdata := c.MustGet("userdata").(user.User)

	if !c.MustGet("protected").(bool) {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(e.ErrInternalError).SetMeta("DeleteTagController.protected")
		return
	}

	// Initialize model struct
	m := &models.DeleteTagModel{
		Ib: params[0],
		ID: params[1],
	}

	// Check the record id and get further info
	err := m.Status()
	if err == e.ErrNotFound {
		c.JSON(e.ErrorMessage(e.ErrNotFound))
		c.Error(err).SetMeta("DeleteTagController.Status")
		return
	} else if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("DeleteTagController.Status")
		return
	}

	// Delete data
	err = m.Delete()
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("DeleteTagController.Delete")
		return
	}

	// Delete redis stuff
	tagsKey := fmt.Sprintf("%s:%d", "tags", m.Ib)
	tagKey := fmt.Sprintf("%s:%d:%d", "tag", m.Ib, m.ID)
	imageKey := fmt.Sprintf("%s:%d", "image", m.Ib)

	err = redis.Cache.Delete(tagsKey, tagKey, imageKey)
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("DeleteTagController.redis.Cache.Delete")
		return
	}

	// response message
	c.JSON(http.StatusOK, gin.H{"success_message": audit.AuditDeleteTag})

	// audit log
	audit := audit.Audit{
		User:   userdata.ID,
		Ib:     m.Ib,
		Type:   audit.ModLog,
		IP:     c.ClientIP(),
		Action: audit.AuditDeleteTag,
		Info:   fmt.Sprintf("%s", m.Name),
	}

	// submit audit
	err = audit.Submit()
	if err != nil {
		c.Error(err).SetMeta("DeleteTagController.audit.Submit")
	}

	return

}
Beispiel #26
0
// UpdateTagController will update a tags properties
func UpdateTagController(c *gin.Context) {
	var err error
	var utf updateTagForm

	// Get parameters from validate middleware
	params := c.MustGet("params").([]uint)

	// get userdata from user middleware
	userdata := c.MustGet("userdata").(user.User)

	if !c.MustGet("protected").(bool) {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(e.ErrInternalError).SetMeta("UpdateTagController.protected")
		return
	}

	err = c.Bind(&utf)
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInvalidParam))
		c.Error(err).SetMeta("UpdateTagController.Bind")
		return
	}

	// Set parameters to UpdateTagModel
	m := models.UpdateTagModel{
		Ib:      params[0],
		ID:      utf.ID,
		Tag:     utf.Tag,
		TagType: utf.Type,
	}

	// Validate input parameters
	err = m.ValidateInput()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error_message": err.Error()})
		c.Error(err).SetMeta("UpdateTagController.ValidateInput")
		return
	}

	// Check tag for duplicate
	err = m.Status()
	if err == e.ErrDuplicateTag {
		c.JSON(http.StatusBadRequest, gin.H{"error_message": err.Error()})
		c.Error(err).SetMeta("UpdateTagController.Status")
		return
	} else if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("UpdateTagController.Status")
		return
	}

	// Update data
	err = m.Update()
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("UpdateTagController.Update")
		return
	}

	// Delete redis stuff
	tagsKey := fmt.Sprintf("%s:%d", "tags", m.Ib)
	tagKey := fmt.Sprintf("%s:%d:%d", "tag", m.Ib, m.ID)
	imageKey := fmt.Sprintf("%s:%d", "image", m.Ib)

	err = redis.Cache.Delete(tagsKey, tagKey, imageKey)
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("UpdateTagController.redis.Cache.Delete")
		return
	}

	// response message
	c.JSON(http.StatusOK, gin.H{"success_message": audit.AuditUpdateTag})

	// audit log
	audit := audit.Audit{
		User:   userdata.ID,
		Ib:     m.Ib,
		Type:   audit.ModLog,
		IP:     c.ClientIP(),
		Action: audit.AuditUpdateTag,
		Info:   fmt.Sprintf("%s", m.Tag),
	}

	// submit audit
	err = audit.Submit()
	if err != nil {
		c.Error(err).SetMeta("UpdateTagController.audit.Submit")
	}

	return

}
Beispiel #27
0
func getIP(c *gin.Context) string {
	iPArray := strings.Split(c.ClientIP(), ":")
	pureIp := iPArray[0]
	return pureIp
}
Beispiel #28
0
// ResetPasswordController will reset an ip
func ResetPasswordController(c *gin.Context) {
	var err error
	var rpf resetPasswordForm

	// Get parameters from validate middleware
	params := c.MustGet("params").([]uint)

	// get userdata from user middleware
	userdata := c.MustGet("userdata").(user.User)

	if !c.MustGet("protected").(bool) {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(e.ErrInternalError).SetMeta("ResetPasswordController.protected")
		return
	}

	err = c.Bind(&rpf)
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInvalidParam))
		c.Error(err).SetMeta("ResetPasswordController.Bind")
		return
	}

	// generate a random password
	password, hash, err := user.RandomPassword()
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("ResetPasswordController.RandomPassword")
		return
	}

	// update the password in the database
	err = user.UpdatePassword(hash, rpf.UID)
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("ResetPasswordController.UpdatePassword")
		return
	}

	// response message
	c.JSON(http.StatusOK, gin.H{"success_message": audit.AuditResetPassword, "password": password})

	// audit log
	audit := audit.Audit{
		User:   userdata.ID,
		Ib:     params[0],
		Type:   audit.UserLog,
		IP:     c.ClientIP(),
		Action: audit.AuditResetPassword,
		Info:   fmt.Sprintf("%d", rpf.UID),
	}

	// submit audit
	err = audit.Submit()
	if err != nil {
		c.Error(err).SetMeta("ResetPasswordController.audit.Submit")
	}

	return

}
Beispiel #29
0
func index(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", gin.H{
		"title": "Main website",
		"ip":    c.ClientIP(),
	})
}
Beispiel #30
0
// BanIPController will ban an ip
func BanIPController(c *gin.Context) {
	var err error
	var bif banIPForm

	// Get parameters from validate middleware
	params := c.MustGet("params").([]uint)

	// get userdata from user middleware
	userdata := c.MustGet("userdata").(user.User)

	if !c.MustGet("protected").(bool) {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(e.ErrInternalError).SetMeta("BanIpController.protected")
		return
	}

	err = c.Bind(&bif)
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInvalidParam))
		c.Error(err).SetMeta("BanIpController.Bind")
		return
	}

	// Initialize model struct
	m := &models.BanIPModel{
		Ib:     params[0],
		Thread: params[1],
		ID:     params[2],
		User:   userdata.ID,
		Reason: bif.Reason,
	}

	// Check the record id and get further info
	err = m.Status()
	if err == e.ErrNotFound {
		c.JSON(e.ErrorMessage(e.ErrNotFound))
		c.Error(err).SetMeta("BanIpController.Status")
		return
	} else if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("BanIpController.Status")
		return
	}

	// add ban to database
	err = m.Post()
	if err != nil {
		c.JSON(e.ErrorMessage(e.ErrInternalError))
		c.Error(err).SetMeta("BanIpController.Post")
		return
	}

	// ban the ip in cloudflare
	go u.CloudFlareBanIP(m.IP, m.Reason)

	// response message
	c.JSON(http.StatusOK, gin.H{"success_message": audit.AuditBanIP})

	// audit log
	audit := audit.Audit{
		User:   userdata.ID,
		Ib:     m.Ib,
		Type:   audit.ModLog,
		IP:     c.ClientIP(),
		Action: audit.AuditBanIP,
		Info:   fmt.Sprintf("%s", m.Reason),
	}

	// submit audit
	err = audit.Submit()
	if err != nil {
		c.Error(err).SetMeta("BanIpController.audit.Submit")
	}

	return

}