Example #1
0
func PutRepositoryImagesV1Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	namespace := ctx.Params(":namespace")
	repository := ctx.Params(":repository")

	r := new(models.Repository)
	if err := r.PutImages(namespace, repository); err != nil {
		log.Error("[REGISTRY API V1] Put images error: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Put V1 images error"})
		return http.StatusBadRequest, result
	}

	if ctx.Req.Header.Get("X-Docker-Token") == "true" {
		username, _, _ := utils.DecodeBasicAuth(ctx.Req.Header.Get("Authorization"))
		token := fmt.Sprintf("Token signature=%v,repository=\"%v/%v\",access=%v",
			utils.MD5(username),
			namespace,
			repository,
			"write")

		ctx.Resp.Header().Set("X-Docker-Token", token)
		ctx.Resp.Header().Set("WWW-Authenticate", token)
	}

	result, _ := json.Marshal(map[string]string{})
	return http.StatusNoContent, result
}
Example #2
0
func PutImageLayerv1Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	imageId := ctx.Params(":imageId")

	basePath := setting.ImagePath
	imagePath := fmt.Sprintf("%v/images/%v", basePath, imageId)
	layerfile := fmt.Sprintf("%v/images/%v/layer", basePath, imageId)

	if !utils.IsDirExist(imagePath) {
		os.MkdirAll(imagePath, os.ModePerm)
	}

	if _, err := os.Stat(layerfile); err == nil {
		os.Remove(layerfile)
	}

	data, _ := ioutil.ReadAll(ctx.Req.Request.Body)
	if err := ioutil.WriteFile(layerfile, data, 0777); err != nil {
		log.Error("[REGISTRY API V1] Put Image Layer File Error: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Put Image Layer File Error"})
		return http.StatusBadRequest, result
	}

	i := new(models.Image)
	if err := i.PutLayer(imageId, layerfile, true, int64(len(data))); err != nil {
		log.Error("[REGISTRY API V1] Put Image Layer File Data Error: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Put Image Layer File Data Error"})
		return http.StatusBadRequest, result
	}

	result, _ := json.Marshal(map[string]string{})
	return http.StatusOK, result
}
func next3(ctx *macaron.Context) {
	fmt.Println("位于处理器 3 中")

	ctx.Next()

	fmt.Println("退出处理器 3")
}
Example #4
0
func myGetCookieHandler(ctx *macaron.Context) string {
	name := ctx.GetCookie("user")
	if name == "" {
		name = "no cookie set"
	}
	return name
}
Example #5
0
func PutImageChecksumV1Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	imageId := ctx.Params(":imageId")

	checksum := strings.Split(ctx.Req.Header.Get("X-Docker-Checksum"), ":")[1]
	payload := strings.Split(ctx.Req.Header.Get("X-Docker-Checksum-Payload"), ":")[1]

	log.Debug("[REGISTRY API V1] Image Checksum : %v", checksum)
	log.Debug("[REGISTRY API V1] Image Payload: %v", payload)

	i := new(models.Image)
	if err := i.PutChecksum(imageId, checksum, true, payload); err != nil {
		log.Error("[REGISTRY API V1] Put Image Checksum & Payload Error: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Put Image Checksum & Payload Error"})
		return http.StatusBadRequest, result
	}

	if err := i.PutAncestry(imageId); err != nil {
		log.Error("[REGISTRY API V1] Put Image Ancestry Error: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Put Image Ancestry Error"})
		return http.StatusBadRequest, result
	}

	result, _ := json.Marshal(map[string]string{})
	return http.StatusOK, result
}
Example #6
0
func GetTagV1Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	namespace := ctx.Params(":namespace")
	repository := ctx.Params(":repository")

	repo := new(models.Repository)
	if has, _, err := repo.Has(namespace, repository); err != nil {
		log.Error("[REGISTRY API V1] Read repository json error: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Get V1 tag failed,wrong name or repository"})
		return http.StatusBadRequest, result
	} else if has == false {
		log.Error("[REGISTRY API V1] Read repository no found. %v/%v", namespace, repository)

		result, _ := json.Marshal(map[string]string{"message": "Get V1 tag failed,read repository no found"})
		return http.StatusNotFound, result
	}

	tag := map[string]string{}

	for _, value := range repo.Tags {
		t := new(models.Tag)
		if err := db.Get(t, value); err != nil {
			log.Error(fmt.Sprintf("[REGISTRY API V1]  %s/%s Tags is not exist", namespace, repository))

			result, _ := json.Marshal(map[string]string{"message": fmt.Sprintf("%s/%s Tags is not exist", namespace, repository)})
			return http.StatusNotFound, result
		}

		tag[t.Name] = t.ImageId
	}

	result, _ := json.Marshal(tag)
	return http.StatusOK, result
}
Example #7
0
func GetImageJSONV1Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	var jsonInfo string
	var payload string
	var err error

	imageId := ctx.Params(":imageId")

	i := new(models.Image)
	if jsonInfo, err = i.GetJSON(imageId); err != nil {
		log.Error("[REGISTRY API V1] Search Image JSON Error: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Search Image JSON Error"})
		return http.StatusNotFound, result
	}

	if payload, err = i.GetChecksumPayload(imageId); err != nil {
		log.Error("[REGISTRY API V1] Search Image Checksum Error: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Search Image Checksum Error"})
		return http.StatusNotFound, result
	}

	ctx.Resp.Header().Set("X-Docker-Checksum-Payload", fmt.Sprintf("sha256:%v", payload))
	ctx.Resp.Header().Set("X-Docker-Size", fmt.Sprint(i.Size))
	ctx.Resp.Header().Set("Content-Length", fmt.Sprint(len(jsonInfo)))

	return http.StatusOK, []byte(jsonInfo)
}
Example #8
0
func PutRepositoryV1Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	username, _, _ := utils.DecodeBasicAuth(ctx.Req.Header.Get("Authorization"))

	namespace := ctx.Params(":namespace")
	repository := ctx.Params(":repository")

	body, err := ctx.Req.Body().String()
	if err != nil {
		log.Error("[REGISTRY API V1] Get request body error: %v", err.Error())
		result, _ := json.Marshal(map[string]string{"message": "Put V1 repository failed,request body is empty"})
		return http.StatusBadRequest, result
	}

	r := new(models.Repository)
	if err := r.Put(namespace, repository, body, ctx.Req.Header.Get("User-Agent"), setting.APIVERSION_V1); err != nil {
		log.Error("[REGISTRY API V1] Put repository error: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": err.Error()})
		return http.StatusBadRequest, result
	}

	if ctx.Req.Header.Get("X-Docker-Token") == "true" {
		token := fmt.Sprintf("Token signature=%v,repository=\"%v/%v\",access=%v",
			utils.MD5(username),
			namespace,
			repository,
			"write")

		ctx.Resp.Header().Set("X-Docker-Token", token)
		ctx.Resp.Header().Set("WWW-Authenticate", token)
	}

	result, _ := json.Marshal(map[string]string{})
	return http.StatusOK, result
}
Example #9
0
func docs(ctx *macaron.Context, locale i18n.Locale, name string) {
	docRoot := models.GetDocByLocale(name, locale.Lang)
	if docRoot == nil {
		ctx.Error(404)
		return
	}

	link := strings.TrimPrefix(ctx.Params("*"), "/")
	link = strings.TrimSuffix(link, ".html")
	link = strings.TrimSuffix(link, ".md")
	ctx.Data["Link"] = "/docs/" + link

	var doc *models.DocNode
	if len(link) == 0 {
		ctx.Redirect("/docs/intro/")
		return
	}

	doc, _ = docRoot.GetNodeByLink(link)
	if doc == nil {
		doc, _ = docRoot.GetNodeByLink(link + "/")
	}
	if doc == nil {
		ctx.Error(404)
		return
	}

	ctx.Data["DocRoot"] = docRoot
	ctx.Data["Doc"] = doc
	ctx.Data["Title"] = doc.Name
	ctx.Data["Data"] = doc.GetContent()
	ctx.HTML(200, "document_"+name, ctx.Data)
}
Example #10
0
func AnonymousTriggerBuild(ctx *macaron.Context) {
	r := ctx.Req
	owner, repo := r.FormValue("owner"), r.FormValue("repo")
	branch := r.FormValue("branch")

	if owner == "" || repo == "" {
		ctx.Error(500, "owner or repo should not be empty")
		return
	}

	var mrepo = &models.Repository{
		Owner: owner,
		Repo:  repo,
	}
	has, err := models.DB.Get(mrepo)
	if err != nil {
		ctx.Error(500, err.Error())
		return
	}
	if has && mrepo.UserId != 0 {
		ctx.Error(500, "This repo is limited to its author to build") // TODO: show who is owned
		return
	}

	if err := triggerBuild(owner, repo, branch, "*****@*****.**"); err != nil {
		ctx.Error(500, err.Error())
		return
	}

	ctx.JSON(200, map[string]string{
		"message": "build is triggered",
	})
}
Example #11
0
func GetTagsListV2Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	namespace := ctx.Params(":namespace")
	repository := ctx.Params(":repository")

	r := new(models.Repository)
	if has, _, err := r.Has(namespace, repository); err != nil || has == false {
		log.Error("[REGISTRY API V2] Repository not found: %v", repository)

		result, _ := json.Marshal(map[string]string{"message": "Repository not found"})
		return http.StatusNotFound, result
	}

	data := map[string]interface{}{}
	tags := []string{}

	data["name"] = fmt.Sprintf("%s/%s", namespace, repository)

	for _, value := range r.Tags {
		t := new(models.Tag)
		if err := t.GetByKey(value); err != nil {
			log.Error("[REGISTRY API V2] Tag not found: %v", err.Error())

			result, _ := json.Marshal(map[string]string{"message": "Tag not found"})
			return http.StatusNotFound, result
		}

		tags = append(tags, t.Name)
	}

	data["tags"] = tags

	result, _ := json.Marshal(data)
	return http.StatusOK, result
}
func GetCustomers(ctx *macaron.Context, x *xorm.Engine) {
	m, _ := url.ParseQuery(ctx.Req.URL.RawQuery)
	glog.V(1).Infof("Debug %#v", m)
	skip := 0
	limit := 0
	var err error

	if v, ok := m["skip"]; ok {
		skip, _ = strconv.Atoi(v[0])
	}

	if v, ok := m["limit"]; ok {
		limit, _ = strconv.Atoi(v[0])
	}

	cs := make([]Customer, 0)
	err = x.Limit(limit, skip).Find(&cs)
	if err != nil {
		glog.V(1).Infof("Get customer from db fail:%s", err.Error())
		ctx.JSON(http.StatusInternalServerError, map[string]string{"message": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, cs)
}
Example #13
0
func handleProfile(ctx *macaron.Context) string {
	switch ctx.Query("op") {
	case "startcpu":
		if err := StartCPUProfile(); err != nil {
			return err.Error()
		}
	case "stopcpu":
		if err := StopCPUProfile(); err != nil {
			return err.Error()
		}
	case "mem":
		dumpMemProf()
	case "gc":
		var buf bytes.Buffer
		DumpGCSummary(&buf)
		return string(buf.Bytes())
	default:
		return fmt.Sprintf(`<p>Available operations:</p>
<ol>
	<li><a href="%s?op=startcpu">Start CPU profile</a></li>
	<li><a href="%s?op=stopcpu">Stop CPU profile</a></li>
	<li><a href="%s?op=mem">Dump memory profile</a></li>
	<li><a href="%s?op=gc">Dump GC summary</a></li>
</ol>`, opt.ProfileURLPrefix, opt.ProfileURLPrefix, opt.ProfileURLPrefix, opt.ProfileURLPrefix)
	}
	ctx.Redirect(opt.ProfileURLPrefix)
	return ""
}
Example #14
0
// Start starts a session by generating new one
// or retrieve existence one by reading session ID from HTTP request if it's valid.
func (m *Manager) Start(ctx *macaron.Context) (RawStore, error) {
	sid := ctx.GetCookie(m.opt.CookieName)
	if len(sid) > 0 && m.provider.Exist(sid) {
		return m.provider.Read(sid)
	}

	sid = m.sessionId()
	sess, err := m.provider.Read(sid)
	if err != nil {
		return nil, err
	}

	cookie := &http.Cookie{
		Name:     m.opt.CookieName,
		Value:    sid,
		Path:     m.opt.CookiePath,
		HttpOnly: true,
		Secure:   m.opt.Secure,
		Domain:   m.opt.Domain,
	}
	if m.opt.CookieLifeTime >= 0 {
		cookie.MaxAge = m.opt.CookieLifeTime
	}
	http.SetCookie(ctx.Resp, cookie)
	ctx.Req.AddCookie(cookie)
	return sess, nil
}
func next1(ctx *macaron.Context) {
	fmt.Println("位于处理器 1 中")

	ctx.Next()

	fmt.Println("退出处理器 1")
}
func next2(ctx *macaron.Context) {
	fmt.Println("位于处理器 2 中")

	ctx.Next()

	fmt.Println("退出处理器 2")
}
//process post alipay return
func AlipayReturn(ctx *macaron.Context, x *xorm.Engine) {
	m, _ := url.ParseQuery(ctx.Req.URL.RawQuery)
	params := map[string]string{}
	for k, v := range m {
		params[k] = v[0]
	}
	result := alipay.Return(params)

	type OrderInfo struct {
		Result  bool
		OrderId string
		GoodId  string
		GoodCnt int64
		Tel     string
		Name    string
		Addr    string
		Sum     float32
	}

	var orderInfo OrderInfo
	orderInfo.Result = false
	if result.Status == -1 || result.Status == -5 || result.Status == -3 {
		ctx.HTML(400, "orderresult", orderInfo)
		return
	}

	o := &Order{Uuid: result.OrderNo}
	has, err := x.Where("status=?", "等待支付").Get(o)
	if err != nil || !has {
		ctx.HTML(400, "orderresult", orderInfo)
		return
	}

	if result.Status != 1 {
		o.Status = "支付失败"
		x.Id(o.Id).Cols("status").Update(o)
		ctx.HTML(400, "orderresult", orderInfo)
		return
	}

	o.Status = "支付成功"
	_, err = x.Id(o.Id).Cols("status").Update(o)
	if err != nil {
		ctx.HTML(400, "orderresult", orderInfo)
		return
	}

	orderInfo.Result = true
	orderInfo.OrderId = o.CusTel + "_" + strconv.FormatInt(o.Id, 10)
	orderInfo.GoodId = strconv.FormatInt(o.GoodId, 10)
	orderInfo.GoodCnt = o.GoodCnt
	orderInfo.Tel = o.CusTel
	orderInfo.Name = o.CusName
	orderInfo.Addr = o.CusAddr
	orderInfo.Sum = o.Sum

	ctx.HTML(200, "orderresult", orderInfo)
	return
}
Example #18
0
func myCacheReadHandler(ctx *macaron.Context, c cache.Cache) interface{} {
	val := c.Get(ctx.Params(":key"))
	if val != nil {
		return val
	} else {
		return fmt.Sprintf("no cache with \"%s\" set", ctx.Params(":key"))
	}
}
func PostGood(ctx *macaron.Context, x *xorm.Engine, g Goods) {
	_, err := x.Insert(g)
	if err != nil {
		glog.V(1).Infof("Insert good %#v fail:%s", g, err.Error())
		ctx.JSON(http.StatusBadRequest, map[string]string{"message": err.Error()})
	}
	ctx.JSON(http.StatusCreated, "SUCCESS")
	return
}
Example #20
0
func DoPupDetail(ctx *macaron.Context) {
	id := ctx.Query("Id")
	pup := findPup(id)
	if pup != nil {
		ctx.Data["IsPup"] = true
		ctx.Data["Pup"] = pup
		ctx.HTML(200, "showDetail")
	}
}
func PostCustomer(ctx *macaron.Context, x *xorm.Engine, c Customer) {
	_, err := x.Insert(c)
	if err != nil {
		glog.V(1).Infof("Insert customer %#v fail:%s", c, err.Error())
		ctx.JSON(http.StatusBadRequest, map[string]string{"message": err.Error()})
	}
	ctx.JSON(http.StatusCreated, "SUCCESS")
	return
}
Example #22
0
func DoDogDetail(ctx *macaron.Context) {
	id := ctx.Query("Id")
	dog := findDog(id)
	if dog != nil {
		ctx.Data["IsDog"] = true
		ctx.Data["Dog"] = dog
		ctx.HTML(200, "showDetail")
	}
}
Example #23
0
func RecentBuild(ctx *macaron.Context) {
	var repos []models.Repository
	err := models.DB.Limit(10).Desc("trigger_at").Where("valid=?", true).Find(&repos)
	if err != nil {
		ctx.Error(500, err.Error())
		return
	}
	ctx.JSON(200, repos)
}
Example #24
0
func RepoList(ctx *macaron.Context) {
	var repos []models.Repository

	// TODO: change limit to paginate
	err := models.DB.Limit(100).Where("valid=?", true).Desc("updated_at").Find(&repos)
	if err != nil {
		ctx.Error(500, err.Error())
		return
	}
	ctx.JSON(200, repos)
}
Example #25
0
// SendRegisterNotifyMail triggers a notify e-mail by admin created a account.
func SendRegisterNotifyMail(c *macaron.Context, u *models.User) {
	body, err := c.HTMLString(string(AUTH_REGISTER_NOTIFY), ComposeTplData(u))
	if err != nil {
		log.Error(4, "HTMLString: %v", err)
		return
	}

	msg := NewMessage([]string{u.Email}, c.Tr("mail.register_notify"), body)
	msg.Info = fmt.Sprintf("UID: %d, registration notify", u.Id)

	SendAsync(msg)
}
Example #26
0
// SignedInID returns the id of signed in user.
func SignedInID(ctx *macaron.Context, sess session.Store) int64 {
	if !models.HasEngine {
		return 0
	}

	// Check access token.
	if IsAPIPath(ctx.Req.URL.Path) {
		tokenSHA := ctx.Query("token")
		if len(tokenSHA) == 0 {
			// Well, check with header again.
			auHead := ctx.Req.Header.Get("Authorization")
			if len(auHead) > 0 {
				auths := strings.Fields(auHead)
				if len(auths) == 2 && auths[0] == "token" {
					tokenSHA = auths[1]
				}
			}
		}

		// Let's see if token is valid.
		if len(tokenSHA) > 0 {
			t, err := models.GetAccessTokenBySHA(tokenSHA)
			if err != nil {
				if models.IsErrAccessTokenNotExist(err) {
					log.Error(4, "GetAccessTokenBySHA: %v", err)
				}
				return 0
			}
			t.Updated = time.Now()
			if err = models.UpdateAccessToekn(t); err != nil {
				log.Error(4, "UpdateAccessToekn: %v", err)
			}
			return t.UID
		}
	}

	uid := sess.Get("uid")
	if uid == nil {
		return 0
	}
	if id, ok := uid.(int64); ok {
		if _, err := models.GetUserByID(id); err != nil {
			if !models.IsErrUserNotExist(err) {
				log.Error(4, "GetUserById: %v", err)
			}
			return 0
		}
		return id
	}
	return 0
}
Example #27
0
func myDatabaseListHandler(ctx *macaron.Context) {
	db, err := gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True&loc=Local")

	if err != nil {
		log.Println("Database Error")
	}

	db.DB()

	contact_entries := []ContactEntry{}
	db.Find(&contact_entries)

	ctx.JSON(200, contact_entries)
}
Example #28
0
func SendUserMail(c *macaron.Context, u *models.User, tpl base.TplName, code, subject, info string) {
	data := ComposeTplData(u)
	data["Code"] = code
	body, err := c.HTMLString(string(tpl), data)
	if err != nil {
		log.Error(4, "HTMLString: %v", err)
		return
	}

	msg := NewMessage([]string{u.Email}, subject, body)
	msg.Info = fmt.Sprintf("UID: %d, %s", u.Id, info)

	SendAsync(msg)
}
Example #29
0
// SendActivateAccountMail sends confirmation e-mail.
func SendActivateEmailMail(c *macaron.Context, u *models.User, email *models.EmailAddress) {
	data := ComposeTplData(u)
	data["Code"] = u.GenerateEmailActivateCode(email.Email)
	data["Email"] = email.Email
	body, err := c.HTMLString(string(AUTH_ACTIVATE_EMAIL), data)
	if err != nil {
		log.Error(4, "HTMLString: %v", err)
		return
	}

	msg := NewMessage([]string{email.Email}, c.Tr("mail.activate_email"), body)
	msg.Info = fmt.Sprintf("UID: %d, activate email", u.Id)

	SendAsync(msg)
}
Example #30
0
func Team(ctx *macaron.Context, locale i18n.Locale) {
	ctx.Data["Link"] = "/team"

	df := models.GetDoc(
		"gitea",
		"team",
		locale.Lang)

	if df == nil {
		ctx.Error(404)
		return
	}

	ctx.Data["Data"] = string(df.Data)
	ctx.HTML(200, "page", ctx.Data)
}