func (repo *CassandraChatRepo) GetUserPerfectMatch(rpf types.PerfectNumber) (types.PerfectNumber, error) {
	// get match for user by id

	var perfectNumber types.PerfectNumber
	var user_id string
	var err error
	err = nil

	sql := fmt.Sprintf(`SELECT user_id, perfect_number 
	FROM perfect_numbers WHERE perfect_number < %v LIMIT 1 ALLOW FILTERING`, rpf.PerfectNumber)

	log.Printf(sql)

	if err = session.Query(sql).Scan(&user_id, &perfectNumber.PerfectNumber); err != nil {
		log.Printf(fmt.Sprintf("CassandraChatRepo.GetUserPerfectMatch() - Error: %v", err.Error()))

		sql := fmt.Sprintf("SELECT user_id, perfect_number FROM perfect_numbers LIMIT 1")

		log.Printf(sql)

		if err = session.Query(sql).Scan(&user_id, &perfectNumber.PerfectNumber); err != nil {
			log.Printf(fmt.Sprintf("CassandraChatRepo.GetUserPerfectMatch() - Error: %v", err.Error()))
		} else {
			if user_id != rpf.UserId.String() {
				perfectNumber.UserId = uuid.Parse(user_id)
			} else {
				err = errors.New("not found")
			}
		}
	} else {
		perfectNumber.UserId = uuid.Parse(user_id)
	}

	return perfectNumber, err
}
Exemple #2
0
func CreateMessage(userId string, receiverId string, mr types.MessageRequest) error {
	var err error
	err = nil

	if err = utilsservice.CheckIfMatchExists(userId, receiverId); err == nil {
		var m types.Message

		m.SenderId = uuid.Parse(userId)
		m.ReceiverId = uuid.Parse(receiverId)
		m.MessageId = uuid.NewRandom()
		m.IsRead = false
		m.Text = strings.Replace(mr.Text, "'", "''", -1)
		if mr.Timestamp != 0 {
			m.Timestamp = int64(time.Unix(mr.Timestamp, 0).UTC().Unix())
		} else {
			m.Timestamp = int64(time.Now().UTC().Unix())
		}

		if err = messageRepo.CreateMessage(m); err == nil {
			err = chatservice.UpdateLastMessageChat(userId, receiverId, m.Text)

			if lastActivity, errA := activityservice.GetUserActivity(receiverId); errA == nil {
				senderUsername, _ := utilsservice.GetUserUsername(userId)
				pushMessage := fmt.Sprintf("%s: %s", senderUsername, m.Text)
				notificationsservice.SendPushNotification(lastActivity.DeviceType, lastActivity.PushToken, pushMessage)
			}
		}
	}

	return err
}
func (repo *CassandraMatchRepo) GetUserMatch(userId string) (types.Match, error) {
	// get match for user by id
	log.Printf(fmt.Sprintf("CassandraMatchRepo.GetUserMatch() - Received userId: %v", userId))

	var match types.Match
	var user_id string
	var matched_user_id string
	var err error
	err = nil

	sql := fmt.Sprintf(`SELECT user_id, matched_user_id, 
	matched_username, timestamp 
	FROM matches WHERE user_id = %v LIMIT 1`, userId)

	log.Printf(sql)

	if err = session.Query(sql).Scan(&user_id, &matched_user_id,
		&match.MatchedUsername, &match.Timestamp); err != nil {
		log.Printf(fmt.Sprintf("CassandraMatchRepo.GetUserMatch() - Error: %v", err.Error()))
	} else {
		match.UserId = uuid.Parse(user_id)
		match.MatchedUserId = uuid.Parse(matched_user_id)
	}

	return match, err
}
func (repo *CassandraMessageRepo) GetUserLastMessageByReceiverId(userId string, receiverId string) (types.Message, error) {
	// get last message for user
	log.Printf(fmt.Sprintf("CassandraMessageRepo.GetUserLastMessageByReceiverId() - Received userId: %v", userId))
	log.Printf(fmt.Sprintf("CassandraMessageRepo.GetUserLastMessageByReceiverId() - Received receiverId: %v", receiverId))

	var messages types.Messages
	var err error
	err = nil

	var message_id, sender_id, receiver_id string
	var text string
	var is_read bool
	var timestamp int64
	var sql string

	//sender messages
	sql = fmt.Sprintf(`SELECT message_id, sender_id, receiver_id, text, is_read, 
	timestamp FROM messages WHERE sender_id = %v AND receiver_id = %v LIMIT 1`, userId, receiverId)

	log.Printf(sql)

	iter := session.Query(sql).Iter()
	for iter.Scan(&message_id, &sender_id, &receiver_id, &text, &is_read, &timestamp) {
		messages = append(messages, types.Message{MessageId: uuid.Parse(message_id), SenderId: uuid.Parse(sender_id),
			ReceiverId: uuid.Parse(receiver_id), Text: text, IsRead: is_read, Timestamp: timestamp})
	}
	if err = iter.Close(); err != nil {
		log.Printf(fmt.Sprintf("CassandraMessageRepo.GetUserLastMessageByReceiverId() - Error: %v", err.Error()))
	}

	//receiver messages
	sql = fmt.Sprintf(`SELECT message_id, sender_id, receiver_id, text, is_read, 
	timestamp FROM messages WHERE sender_id = %v AND receiver_id = %v`, receiverId, userId)

	log.Printf(sql)

	iter2 := session.Query(sql).Iter()
	for iter2.Scan(&message_id, &sender_id, &receiver_id, &text, &is_read, &timestamp) {
		messages = append(messages, types.Message{MessageId: uuid.Parse(message_id), SenderId: uuid.Parse(sender_id),
			ReceiverId: uuid.Parse(receiver_id), Text: text, IsRead: is_read, Timestamp: timestamp})
	}
	if err = iter2.Close(); err != nil {
		log.Printf(fmt.Sprintf("CassandraMessageRepo.GetUserLastMessageByReceiverId() - Error: %v", err.Error()))
	}

	if messages != nil {
		sort.Sort(ByTimestamp(messages))
	}

	var message types.Message

	if len(messages) > 0 {
		message = messages[0]
	}

	return message, err
}
Exemple #5
0
func TestUniqueKeyCreation(t *testing.T) {
	uniqueKey := NewUniqueKey("")
	if uuid.Parse(uniqueKey.String()) == nil {
		t.Error("Invalid uuid generated")
	}
	uniqueKey.Next()
	if uuid.Parse(uniqueKey.String()) == nil {
		t.Error("Invalid uuid generated")
	}
}
Exemple #6
0
func CreateMatch(mr types.MatchRequest) error {
	var err error
	err = nil

	if err = utilsservice.CheckIfUserExists(mr.FirstUserId); err == nil {
		if err = utilsservice.CheckIfUserExists(mr.SecondUserId); err == nil {
			var firstUsername string
			var secondUsername string

			if firstUsername, err = utilsservice.GetUserUsername(mr.FirstUserId); err == nil {
				if secondUsername, err = utilsservice.GetUserUsername(mr.SecondUserId); err == nil {
					var m types.Match

					m.UserId = uuid.Parse(mr.FirstUserId)
					m.MatchedUserId = uuid.Parse(mr.SecondUserId)
					m.MatchedUsername = secondUsername
					m.Timestamp = int64(time.Now().UTC().Unix())

					//create first match
					if err = chatRepo.CreateMatch(m); err == nil {
						m.UserId = uuid.Parse(mr.SecondUserId)
						m.MatchedUserId = uuid.Parse(mr.FirstUserId)
						m.MatchedUsername = firstUsername
						m.Timestamp = int64(time.Now().UTC().Unix())

						//create second match
						if err = chatRepo.CreateMatch(m); err == nil {
							var cr types.ChatRequest

							//create chat
							cr.FirstUserId = mr.FirstUserId
							cr.SecondUserId = mr.SecondUserId
							err = CreateChat(cr)

							//send push message to first user
							if lastActivity, errA := activityservice.GetUserActivity(mr.FirstUserId); errA == nil {
								notificationsservice.SendPushNotification(lastActivity.DeviceType, lastActivity.PushToken, "you've been matched!")
							}

							//send push message to second user
							if lastActivity, errA := activityservice.GetUserActivity(mr.SecondUserId); errA == nil {
								notificationsservice.SendPushNotification(lastActivity.DeviceType, lastActivity.PushToken, "you've been matched!")
							}
						}
					}
				}
			}
		}
	}

	return err
}
Exemple #7
0
// LookUpServers attempts to return identifiers matching a pattern
func (c *ScalewayCache) LookUpServers(needle string, acceptUUID bool) []string {
	c.Lock.Lock()
	defer c.Lock.Unlock()

	var res []string
	var exactMatches []string

	if acceptUUID && uuid.Parse(needle) != nil {
		res = append(res, needle)
	}

	nameRegex := regexp.MustCompile(`(?i)` + regexp.MustCompile(`[_-]`).ReplaceAllString(needle, ".*"))
	for identifier, name := range c.Servers {
		if name == needle {
			exactMatches = append(exactMatches, identifier)
		}
		if strings.HasPrefix(identifier, needle) || nameRegex.MatchString(name) {
			res = append(res, identifier)
		}
	}

	if len(exactMatches) == 1 {
		return exactMatches
	}

	return utils.RemoveDuplicates(res)
}
Exemple #8
0
func request_get_NEAREST(q *btrdb.Quasar, w http.ResponseWriter, r *http.Request) {
	atomic.AddInt32(&outstandingHttpReqs, 1)
	defer func() {
		atomic.AddInt32(&outstandingHttpReqs, -1)
	}()
	r.ParseForm()
	ids := r.Form.Get(":uuid")
	id := uuid.Parse(ids)
	if id == nil {
		doError(w, "malformed uuid")
		return
	}
	t, ok, msg := parseInt(r.Form.Get("time"), -(16 << 56), (48 << 56))
	if !ok {
		doError(w, "bad time: "+msg)
		return
	}
	bws := r.Form.Get("backwards")
	bw := bws != ""
	rec, _, err := q.QueryNearestValue(id, t, bw, btrdb.LatestGeneration)
	if err != nil {
		doError(w, "Bad query: "+err.Error())
		return
	}
	w.Write([]byte(fmt.Sprintf("[%d, %f]", rec.Time, rec.Val)))
}
Exemple #9
0
func parseRow(row connection.Row) (Record, error) {
	r := Record{}
	var rUUID, dUUID string
	var rtID int32
	var pID int32
	var jsonBuf []byte
	err := row.Scan(&rUUID, &dUUID, &r.Name, &jsonBuf, &rtID, &r.Date, &pID, &r.Added)
	if err != nil {
		return r, err
	}
	err = json.Unmarshal(jsonBuf, &r.Args)
	if err != nil {
		return r, err
	}
	r.UUID = uuid.Parse(rUUID)
	r.Domain, err = domains.GetByUUID(dUUID).One()
	if err != nil {
		return r, err
	}
	r.Type, err = types.GetByID(rtID).One()
	if err != nil {
		return r, err
	}
	// ignore error as we dont need a Parser
	p, _ := parser.Get(parser.GetByID(), pID)
	r.Parser = p
	return r, nil
}
Exemple #10
0
func getTestMessageWithFunnyFields() *message.Message {
	field, _ := message.NewField(`"foo`, "bar\n", "")
	field1, _ := message.NewField(`"number`, 64, "")
	field2, _ := message.NewField("\xa3", "\xa3", "")
	field3, _ := message.NewField("idField", "1234", "")

	msg := &message.Message{}
	msg.SetType("TEST")
	loc, _ := time.LoadLocation("UTC")
	t, _ := time.ParseInLocation("2006-01-02T15:04:05.000Z", "2013-07-16T15:49:05.070Z",
		loc)
	msg.SetTimestamp(t.UnixNano())
	msg.SetUuid(uuid.Parse("87cf1ac2-e810-4ddf-a02d-a5ce44d13a85"))
	msg.SetLogger("GoSpec")
	msg.SetSeverity(int32(6))
	msg.SetPayload("Test Payload")
	msg.SetEnvVersion("0.8")
	msg.SetPid(14098)
	msg.SetHostname("hostname")
	msg.AddField(field)
	msg.AddField(field1)
	msg.AddField(field2)
	msg.AddField(field3)

	return msg
}
Exemple #11
0
func (m *OpsConfigManager) handleNeighborUpdate(update ovsdb.TableUpdate) []*server.GrpcRequest {
	_, id, _ := m.getBGPRouterUUID()
	addrs, ids, err := m.getBGPNeighborUUIDs(id)
	if err != nil {
		return nil
	}
	reqs := make([]*server.GrpcRequest, 0, len(addrs))
	for k, v := range update.Rows {
		for idx, id := range ids {
			if uuid.Equal(id, uuid.Parse(k)) {
				asn, ok := v.New.Fields["remote_as"].(float64)
				if !ok {
					log.Debugf("remote-as is not configured yet")
					continue
				}
				reqs = append(reqs, server.NewGrpcRequest(server.REQ_MOD_NEIGHBOR, "", bgp.RouteFamily(0), &api.ModNeighborArguments{
					Operation: api.Operation_ADD,
					Peer: &api.Peer{
						Conf: &api.PeerConf{
							NeighborAddress: addrs[idx].String(),
							PeerAs:          uint32(asn),
						},
					},
				}))
			}
		}
	}
	return reqs
}
Exemple #12
0
func (m *OpsConfigManager) getBGPNeighborUUIDs(id uuid.UUID) ([]net.IP, []uuid.UUID, error) {
	global, ok := m.cache["BGP_Router"]
	if !ok {
		return nil, nil, fmt.Errorf("BGP_Router table not found")
	}
	for k, v := range global {
		if uuid.Equal(id, uuid.Parse(k)) {
			neighbors := v.Fields["bgp_neighbors"].(ovsdb.OvsMap).GoMap
			if len(neighbors) < 1 {
				return nil, nil, fmt.Errorf("no bgp neighbor configured")
			}
			addrs := make([]net.IP, 0, len(neighbors))
			ids := make([]uuid.UUID, 0, len(neighbors))
			for k, v := range neighbors {
				addrs = append(addrs, net.ParseIP(k.(string)))
				id := extractUUID(v)
				if id == nil {
					return nil, nil, fmt.Errorf("invalid uuid schema")
				}
				ids = append(ids, id)
			}
			return addrs, ids, nil
		}
	}
	return nil, nil, fmt.Errorf("not found")
}
func CreateAccelerations(userId string, accelerations types.AccelerationsRequest) error {
	var err error
	err = nil

	if err = utilsservice.CheckIfUserExists(userId); err == nil {
		for _, ar := range accelerations {
			var a types.Acceleration
			a.UserId = uuid.Parse(userId)
			a.X = ar.X
			a.Y = ar.Y
			a.Z = ar.Z

			if ar.Timestamp != 0 {
				a.Timestamp = int64(time.Unix(ar.Timestamp, 0).UTC().Unix())
			} else {
				a.Timestamp = int64(time.Now().UTC().Unix())
			}

			err = accelerationRepo.CreateAcceleration(a)

			if err != nil {
				break
			}
		}

		//increment walking progress for test users
		if err == nil {
			if user, errU := userservice.GetUser(userId); errU == nil {
				if userExtraInfo, errU := userservice.GetUserExtraInfo(userId); errU == nil {
					if userExtraInfo.WalkingProgress < 100 {
						if user.IsTest {
							var userExtraInfoRequest types.UserExtraInfoRequest

							if userExtraInfo.WalkingProgress >= 95 {
								userExtraInfoRequest.WalkingProgress = 100
							} else {
								userExtraInfoRequest.WalkingProgress = userExtraInfo.WalkingProgress + 3
							}

							if errU := userservice.UpdateUserExtraInfo(userId, userExtraInfoRequest); errU != nil {
								log.Printf(fmt.Sprintf("AccelerationService.CreateAccelerations() - Error: %v", errU.Error()))
							}
						} else {
							if accelerations != nil && len(accelerations) > 1 {
								kafkaMessage := fmt.Sprintf("%v,%v,%v", userId, accelerations[0].Timestamp, accelerations[len(accelerations)-1].Timestamp)
								kafkaservice.ProduceMessage(kafkaMessage)
							}
						}
					}
				} else {
					log.Printf(fmt.Sprintf("AccelerationService.CreateAccelerations() - Error: %v", errU.Error()))
				}
			} else {
				log.Printf(fmt.Sprintf("AccelerationService.CreateAccelerations() - Error: %v", errU.Error()))
			}
		}
	}

	return err
}
Exemple #14
0
func initdb() {
	if *showquery {
		// don't need a database for printing queries
		return
	} else if *dbname == "" {
		log.Fatal("must specify database with -db flag")
	}

	var err error
	db, err = sql.Open("sqlite3", *dbname)
	fatalif(err)

	if *simidstr == "" {
		ids, err := query.SimIds(db)
		fatalif(err)
		simid = ids[0]
	} else {
		simid = uuid.Parse(*simidstr)
		if simid == nil {
			log.Fatalf("invalid simid '%s'", *simidstr)
		}
	}

	post.Process(db)
}
Exemple #15
0
func (repo *CassandraUserRepo) GetUser(userId string) (types.User, error) {
	// get user by id
	var user types.User
	var user_id string
	var err error
	err = nil

	sql := fmt.Sprintf(`SELECT user_id, username, facebook_access_token, 
	twitter_access_token, google_access_token, push_token, 
	device_type, email, password, is_test, is_anonymous, gender_preference, 
	timestamp FROM users WHERE user_id = %v LIMIT 1`, userId)

	log.Printf(sql)

	if err = session.Query(sql).Scan(&user_id,
		&user.Username, &user.FacebookAccessToken, &user.TwitterAccessToken, &user.GoogleAccessToken,
		&user.PushToken, &user.DeviceType, &user.Email,
		&user.Password, &user.IsTest, &user.IsAnonymous, &user.GenderPreference, &user.Timestamp); err != nil {
		log.Printf(fmt.Sprintf("CassandraUserRepo.GetUser() - Error: %v", err.Error()))
	} else {
		user.UserId = uuid.Parse(user_id)
	}

	return user, err
}
func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byte, keyId []byte, err error) {
	keyId = uuid.Parse(keyProtected.Id)
	mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
	if err != nil {
		return nil, nil, err
	}

	iv, err := hex.DecodeString(keyProtected.Crypto.CipherParams.IV)
	if err != nil {
		return nil, nil, err
	}

	cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
	if err != nil {
		return nil, nil, err
	}

	derivedKey, err := getKDFKey(keyProtected.Crypto, auth)
	if err != nil {
		return nil, nil, err
	}

	calculatedMAC := Sha3(derivedKey[16:32], cipherText)
	if !bytes.Equal(calculatedMAC, mac) {
		return nil, nil, errors.New("Decryption failed: MAC mismatch")
	}

	plainText, err := aesCBCDecrypt(Sha3(derivedKey[:16])[:16], cipherText, iv)
	if err != nil {
		return nil, nil, err
	}
	return plainText, keyId, err
}
func (repo *CassandraAccelerationRepo) GetAccelerations(userId string) (types.Accelerations, error) {
	// get accelerations
	var accelerations types.Accelerations
	var err error
	err = nil

	var user_id string
	var x, y, z float64
	var timestamp int64

	sql := fmt.Sprintf("SELECT user_id, x, y, z, timestamp FROM accelerations WHERE user_id = %v", userId)

	log.Printf(sql)

	iter := session.Query(sql).Iter()
	for iter.Scan(&user_id, &x, &y, &z, &timestamp) {
		accelerations = append(accelerations, types.Acceleration{UserId: uuid.Parse(user_id), X: x, Y: y, Z: z, Timestamp: timestamp})
	}

	if err = iter.Close(); err != nil {
		log.Printf(fmt.Sprintf("CassandraAccelerationRepo.GetAccelerations() - Error: %v", err.Error()))
	}

	return accelerations, err
}
Exemple #18
0
func (k *Key) UnmarshalJSON(j []byte) (err error) {
	keyJSON := new(plainKeyJSON)
	err = json.Unmarshal(j, &keyJSON)
	if err != nil {
		return err
	}

	u := new(uuid.UUID)
	*u = uuid.Parse(keyJSON.Id)
	k.Id = *u
	addr, err := hex.DecodeString(keyJSON.Address)
	if err != nil {
		return err
	}

	privkey, err := hex.DecodeString(keyJSON.PrivateKey)
	if err != nil {
		return err
	}

	k.Address = common.BytesToAddress(addr)
	k.PrivateKey = ToECDSA(privkey)

	return nil
}
Exemple #19
0
func receiveGreeting(conn net.Conn) string {
	peerUUID := make([]byte, 36)
	read, err := conn.Read(peerUUID)

	if read != 36 {
		// FIXME does this mean the buffer hasn't filled or what?
		// treat this as invalid right now [and investigate]
		return ""
	}

	if err != nil {
		return ""
	}

	parsed := uuid.Parse(string(peerUUID))
	if parsed == nil {
		// invalid uuid; die
		return ""
	}

	debug("received greeting from ", conn.RemoteAddr(), ": ", parsed.String())

	// this is valid, return it
	return parsed.String()
}
// LastEventHTTP handles HTTP requests for looking up a job's last event. The
// job is looked up by its invocation ID. JSON is written to the response body
// in the following format:
//
// 		{
// 			"state" : {
// 				"uuid" : "",
// 				"status" : "",
// 				"completion_date" : ""
// 			}
//		}
//
// 'uuid' will be in the normal UUID format of 32 hex digits in 5 groups
//  delimited by '-'. For example: 'bf6ff4a0-7bcf-11e4-b116-123b93f75cba'.
//
// 'status' will be a one of 'Submitted', 'Running', 'Completed', or 'Failed'.
//
// 'completion_date' will be a timestamp that looks like
// '2006-01-02T15:04:05Z07:00'.
func (h *HTTPAPI) LastEventHTTP(writer http.ResponseWriter, request *http.Request) {
	logger.Printf("Handling GET request for %s", request.URL.Path)
	baseName := path.Base(request.URL.Path)
	if baseName == "" {
		WriteRequestError(writer, "The path must contain an invocation UUID")
		return
	}
	logger.Printf("Requested job UUID: %s", baseName)
	if uuid.Parse(baseName) == nil {
		WriteRequestError(writer, fmt.Sprintf("The base of the path must be a UUID: %s", baseName))
		return
	}
	jr, err := h.d.GetJobByInvocationID(baseName)
	if err != nil {
		WriteRequestError(writer, err.Error())
		return
	}
	if jr == nil {
		writer.WriteHeader(http.StatusNotFound)
		writer.Write([]byte(fmt.Sprintf("Job %s was not found", baseName)))
		return
	}
	lastCondorJobEvent, err := h.d.GetLastCondorJobEvent(jr.ID)
	if err != nil {
		writer.WriteHeader(http.StatusNotFound)
		writer.Write([]byte(fmt.Sprintf("Last event for job %s using invocation %s was not found", jr.ID, baseName)))
		return
	}
	lastJobEvent, err := h.d.GetCondorJobEvent(lastCondorJobEvent.CondorJobEventID)
	if err != nil {
		writer.WriteHeader(http.StatusNotFound)
		writer.Write([]byte(fmt.Sprintf("JobEvent %s was not found for last event lookup", lastCondorJobEvent.CondorJobEventID)))
		return
	}
	condorEvent, err := h.d.GetCondorEvent(lastJobEvent.CondorEventID)
	if err != nil {
		writer.WriteHeader(http.StatusNotFound)
		writer.Write([]byte(fmt.Sprintf("CondorEvent %s was not found for last event lookup", lastJobEvent.CondorEventID)))
		return
	}
	appEvent := &Event{
		EventNumber:  condorEvent.EventNumber,
		CondorID:     jr.CondorID,
		AppID:        jr.AppID,
		InvocationID: jr.InvocationID,
		User:         jr.Submitter,
		EventName:    condorEvent.EventName,
		ExitCode:     jr.ExitCode,
	}
	jobState := NewJobState(appEvent)
	marshalled, err := json.Marshal(jobState)
	if err != nil {
		writer.WriteHeader(http.StatusInternalServerError)
		writer.Write([]byte(err.Error()))
		return
	}
	logger.Printf("Response for last event lookup by invocation %s:\n%s", baseName, string(marshalled[:]))
	writer.Write(marshalled)

}
// JobHTTPGet is responsible for retrieving a Job from the database and returning
// its record as a JSON object. The UUID for the job is extracted from the basename
// of the URL path and must be a valid UUID.
func (h *HTTPAPI) JobHTTPGet(writer http.ResponseWriter, request *http.Request) {
	logger.Printf("Handling GET request for %s", request.URL.Path)
	baseName := path.Base(request.URL.Path)
	if baseName == "" {
		WriteRequestError(writer, "The path must contain a job UUID")
		return
	}
	logger.Printf("Requested job UUID: %s", baseName)
	if uuid.Parse(baseName) == nil {
		WriteRequestError(writer, fmt.Sprintf("The base of the path must be a UUID: %s", baseName))
		return
	}
	jr, err := h.d.GetJob(baseName)
	if err != nil {
		WriteRequestError(writer, err.Error())
		return
	}
	if jr == nil {
		writer.WriteHeader(http.StatusNotFound)
		writer.Write([]byte(fmt.Sprintf("Job %s was not found", baseName)))
		return
	}
	marshalled, err := json.Marshal(jr)
	if err != nil {
		writer.WriteHeader(http.StatusInternalServerError)
		writer.Write([]byte(err.Error()))
		return
	}
	logger.Printf("Response for job lookup by UUID %s:\n%s", baseName, string(marshalled[:]))
	writer.Write(marshalled)
}
Exemple #22
0
func getOrPreparePod(args []string) (*jetpack.Pod, error) {
	switch len(args) {
	case 0:
		return nil, ErrUsage
	case 1:
		if id := uuid.Parse(args[0]); id != nil {
			// Pod UUID
			return Host.GetPod(id)
		}
		fallthrough
	default:
		if pm, err := getPodManifest(args); err != nil {
			return nil, err
		} else if pod, err := Host.CreatePod(pm); err != nil {
			return nil, err
		} else {
			if SaveID != "" {
				if err := ioutil.WriteFile(SaveID, []byte(pod.UUID.String()), 0644); err != nil {
					return nil, err
				}
			}
			return pod, nil
		}
	}
}
func (m *ApiClient) FQNameByUuid(id string) ([]string, error) {
	obj, err := m.db.GetByUuid(uuid.Parse(id))
	if err != nil {
		return []string{}, err
	}
	return obj.GetFQName(), nil
}
Exemple #24
0
// ResetUserPassword is a route which is called when accessing the page generated dispatched with
// account recovery emails.
func ResetUserPassword(w http.ResponseWriter, r *http.Request) {
	var user User
	r.ParseForm()
	user.Password = r.PostFormValue("password")

	vars := mux.Vars(r)
	id, err := strconv.Atoi(vars["id"])
	if err != nil {
		log.Println("resetuserpassword id: ", err)
		rend.JSON(w, http.StatusBadRequest, map[string]interface{}{"error": "User ID could not be parsed from request URL."})
		return
	}
	user.ID = int64(id)

	// FIXME entry?
	entry, err := user.Get()
	if err != nil {
		log.Println("resetuserpassword get: ", err)
		if err.Error() == "not found" {
			rend.JSON(w, http.StatusBadRequest, map[string]interface{}{"error": "User with that ID does not exist."})
			return
		}
		rend.JSON(w, http.StatusInternalServerError, map[string]interface{}{"error": "Internal server error"})
		return
	}
	// this ensures that accounts won't be compromised by posting recovery string as empty,
	// which would otherwise result in succesful password reset
	UUID := uuid.Parse(vars["recovery"])
	if UUID == nil {
		log.Println("there was a problem trying to verify password reset UUID for", entry.Email)
		rend.JSON(w, http.StatusBadRequest, map[string]interface{}{"error": "Could not parse UUID from the request."})
		return
	}
	if entry.Recovery == vars["recovery"] {
		entry.Password = user.Password
		digest, err := GenerateHash(entry.Password)
		if err != nil {
			log.Println("resertuserpassword genhash: ", err)
			rend.JSON(w, http.StatusInternalServerError, map[string]interface{}{"error": "Internal server error"})
			return
		}
		entry.Digest = digest
		entry.Recovery = " "
		_, err = user.Update(r)
		if err != nil {
			log.Println("resetuserpassword update: ", err)
			rend.JSON(w, http.StatusInternalServerError, map[string]interface{}{"error": "Internal server error"})
			return
		}
		switch root(r) {
		case "api":
			rend.JSON(w, http.StatusOK, map[string]interface{}{"success": "Password was updated successfully."})
			return
		case "user":
			http.Redirect(w, r, "/user/login", http.StatusFound)
			return
		}
	}
}
Exemple #25
0
func (this *Session) SetAuthenticated(result bool) {
	if !result {
		this.Disconnect("Error: Authentication to Minecraft.net Failed")
		return
	}
	this.uuid = uuid.Parse(FormatUUID(this.profile.Id))
	if this.server.SessionRegistry.HasName(this.name) {
		this.Disconnect(minecraft.Colorize(this.server.localizer.LocaleLoggedIn()))
		return
	}
	if this.server.SessionRegistry.HasUuid(this.uuid) {
		this.Disconnect(minecraft.Colorize(this.server.localizer.LocaleLoggedIn()))
		return
	}
	if this.server.MaxPlayers() > 1 && this.server.SessionRegistry.Len() >= int(this.server.MaxPlayers()) {
		this.Disconnect(minecraft.Colorize(this.server.localizer.LocaleFull()))
		return
	}
	servers := this.server.router.Route(this.serverAddress)
	activeServers := []string{}
	for _, serverName := range servers {
		if !this.server.connect.HasServer(serverName) {
			continue
		}
		activeServers = append(activeServers, serverName)
	}
	if len(activeServers) == 0 {
		this.Disconnect(minecraft.Colorize(this.server.localizer.LocaleOffline()))
		return
	}
	serverName := activeServers[RandomInt(len(activeServers))]
	server := this.server.connect.Server(serverName)
	if server == nil {
		this.Disconnect("Error: Outbound Server Mismatch: " + serverName)
		return
	}
	addResult := this.server.connect.AddLocalPlayer(this.name, this.uuid)
	if addResult == 0 {
		this.Disconnect(minecraft.Colorize(this.server.localizer.LocaleLoggedIn()))
		return
	} else if addResult == -1 {
		this.Disconnect(minecraft.Colorize(this.server.localizer.LocaleLoggedIn()))
		return
	}
	this.state = STATE_INIT
	if this.protocolVersion >= 5 {
		this.Write(minecraft.NewPacketClientLoginSuccess(FormatUUID(this.profile.Id), this.name))
	} else {
		this.Write(minecraft.NewPacketClientLoginSuccess(this.profile.Id, this.name))
	}
	if this.protocol17 {
		this.pipeline.Replace("registry", minecraft.PlayPacketServerCodec17)
	} else {
		this.pipeline.Replace("registry", minecraft.PlayPacketServerCodec)
	}
	this.connCodec.SetTimeout(20 * time.Second)
	this.server.SessionRegistry.Register(this)
	this.Redirect(server)
}
Exemple #26
0
func getPod(name string) (*jetpack.Pod, error) {
	if id := uuid.Parse(name); id != nil {
		// Pod UUID
		return Host.GetPod(id)
	}
	// TODO: pod name
	return nil, ErrUsage
}
func (m *ApiClient) FindByUuid(typename string, id string) (contrail.IObject, error) {
	obj, err := m.db.GetByUuid(uuid.Parse(id))
	if err != nil {
		return nil, err
	}
	m.interceptGet(obj)
	return obj, nil
}
func (m *ApiClient) DeleteByUuid(typename string, id string) error {
	obj, err := m.db.GetByUuid(uuid.Parse(id))
	if err != nil {
		return err
	}
	// Ensure the object has no children and/or back_refs
	return m.db.Delete(obj)
}
Exemple #29
0
func getClientSubscriberID(cl *data.QueueClient) bool {
	sClData := string(cl.DataIn)
	cUuid := uuid.Parse(sClData)
	if cUuid != nil {
		cl.SubscriberId = cUuid
		return true
	}
	return false
}
Exemple #30
0
// uUIDFromPath extracts the upload UUID from a given path
// If the UUID is the last path component, this is the containing
// directory for all upload files
func uUIDFromPath(path string) (string, bool) {
	components := strings.Split(path, "/")
	for i := len(components) - 1; i >= 0; i-- {
		if uuid := uuid.Parse(components[i]); uuid != nil {
			return uuid.String(), i == len(components)-1
		}
	}
	return "", false
}