How to use halt method of HTTP Package

Best Webmock_ruby code snippet using HTTP.halt

app.rb

Source:app.rb Github

copy

Full Screen

...162 is_error: false,163 message: message,164 }.to_json165 end166 def halt_with_error(status = 500, message = 'unknown')167 headers = {168 'Content-Type' => 'application/json',169 }170 response = {171 is_error: true,172 message: message,173 }174 halt status, headers, response.to_json175 end176 end177 post '/initialize' do178 db.query('TRUNCATE seat_reservations')179 db.query('TRUNCATE reservations')180 db.query('TRUNCATE users')181 content_type :json182 {183 available_days: AVAILABLE_DAYS,184 language: 'ruby',185 }.to_json186 end187 get '/api/settings' do188 payment_api = ENV['PAYMENT_API'] || 'http://127.0.0.1:5000'189 content_type :json190 { payment_api: payment_api }.to_json191 end192 get '/api/stations' do193 stations = db.query('SELECT * FROM `station_master` ORDER BY `id`').map do |station|194 station.slice(:id, :name, :is_stop_express, :is_stop_semi_express, :is_stop_local)195 end196 content_type :json197 stations.to_json198 end199 get '/api/train/search' do200 date = Time.iso8601(params[:use_at]).getlocal201 halt_with_error 404, '予約可能期間外です' unless check_available_date(date)202 from_station = db.xquery(203 'SELECT * FROM station_master WHERE name = ?',204 params[:from],205 ).first206 if from_station.nil?207 puts 'fromStation: no rows'208 halt_with_error 400, 'fromStation: no rows'209 end210 to_station = db.xquery(211 'SELECT * FROM station_master WHERE name = ?',212 params[:to],213 ).first214 if to_station.nil?215 puts 'toStation: no rows'216 halt_with_error 400, 'toStation: no rows'217 end218 is_nobori = from_station[:distance] > to_station[:distance]219 usable_train_class_list = get_usable_train_class_list(from_station, to_station)220 train_list = if params[:train_class].nil? || params[:train_class].empty?221 db.xquery(222 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` IN (?) AND `is_nobori` = ?',223 date.strftime('%Y/%m/%d'),224 usable_train_class_list,225 is_nobori,226 )227 else228 db.xquery(229 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` IN (?) AND `is_nobori` = ? AND `train_class` = ?',230 date.strftime('%Y/%m/%d'),231 usable_train_class_list,232 is_nobori,233 params[:train_class],234 )235 end236 stations = db.xquery(237 "SELECT * FROM `station_master` ORDER BY `distance` #{is_nobori ? 'DESC' : 'ASC'}",238 )239 puts "From #{from_station}"240 puts "To #{to_station}"241 train_search_response_list = []242 train_list.each do |train|243 is_seeked_to_first_station = false244 is_contains_origin_station = false245 is_contains_dest_station = false246 i = 0247 stations.each do |station|248 unless is_seeked_to_first_station249 # 駅リストを列車の発駅まで読み飛ばして頭出しをする250 # 列車の発駅以前は止まらないので無視して良い251 if station[:name] == train[:start_station]252 is_seeked_to_first_station = true253 else254 next255 end256 end257 if station[:id] == from_station[:id]258 # 発駅を経路中に持つ編成の場合フラグを立てる259 is_contains_origin_station = true260 end261 if station[:id] == to_station[:id]262 if is_contains_origin_station263 # 発駅と着駅を経路中に持つ編成の場合264 is_contains_dest_station = true265 else266 # 出発駅より先に終点が見つかったとき267 puts 'なんかおかしい'268 end269 break270 end271 if station[:name] == train[:last_station]272 # 駅が見つからないまま当該編成の終点に着いてしまったとき273 break274 end275 i += 1276 end277 if is_contains_origin_station && is_contains_dest_station278 # 列車情報279 departure = db.xquery(280 'SELECT `departure` FROM `train_timetable_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ? AND `station` = ?',281 date.strftime('%Y/%m/%d'),282 train[:train_class],283 train[:train_name],284 from_station[:name],285 cast: false,286 ).first287 departure_date = Time.parse("#{date.strftime('%Y/%m/%d')} #{departure[:departure]} +09:00 JST")288 next unless date < departure_date289 arrival = db.xquery(290 'SELECT `arrival` FROM `train_timetable_master` WHERE date = ? AND `train_class` = ? AND `train_name` = ? AND `station` = ?',291 date.strftime('%Y/%m/%d'),292 train[:train_class],293 train[:train_name],294 to_station[:name],295 cast: false,296 ).first297 premium_avail_seats = get_available_seats(train, from_station, to_station, 'premium', false)298 premium_smoke_avail_seats = get_available_seats(train, from_station, to_station, 'premium', true)299 reserved_avail_seats = get_available_seats(train, from_station, to_station, 'reserved', false)300 reserved_smoke_avail_seats = get_available_seats(train, from_station, to_station, 'reserved', true)301 premium_avail = '○'302 if premium_avail_seats.length.zero?303 premium_avail = '×'304 elsif premium_avail_seats.length < 10305 premium_avail = '△'306 end307 premium_smoke_avail = '○'308 if premium_smoke_avail_seats.length.zero?309 premium_smoke_avail = '×'310 elsif premium_smoke_avail_seats.length < 10311 premium_smoke_avail = '△'312 end313 reserved_avail = '○'314 if reserved_avail_seats.length.zero?315 reserved_avail = '×'316 elsif reserved_avail_seats.length < 10317 reserved_avail = '△'318 end319 reserved_smoke_avail = '○'320 if reserved_smoke_avail_seats.length.zero?321 reserved_smoke_avail = '×'322 elsif reserved_smoke_avail_seats.length < 10323 reserved_smoke_avail = '△'324 end325 # 空席情報326 seat_availability = {327 premium: premium_avail,328 premium_smoke: premium_smoke_avail,329 reserved: reserved_avail,330 reserved_smoke: reserved_smoke_avail,331 non_reserved: '○',332 }333 # 料金計算334 premium_fare = fare_calc(date, from_station[:id], to_station[:id], train[:train_class], 'premium')335 premium_fare = premium_fare * params[:adult].to_i + premium_fare / 2 * params[:child].to_i336 reserved_fare = fare_calc(date, from_station[:id], to_station[:id], train[:train_class], 'reserved')337 reserved_fare = reserved_fare * params[:adult].to_i + reserved_fare / 2 * params[:child].to_i338 non_reserved_fare = fare_calc(date, from_station[:id], to_station[:id], train[:train_class], 'non-reserved')339 non_reserved_fare = non_reserved_fare * params[:adult].to_i + non_reserved_fare / 2 * params[:child].to_i340 fare_information = {341 premium: premium_fare,342 premium_smoke: premium_fare,343 reserved: reserved_fare,344 reserved_smoke: reserved_fare,345 non_reserved: non_reserved_fare,346 }347 train_search_response = {348 train_class: train[:train_class],349 train_name: train[:train_name],350 start: train[:start_station],351 last: train[:last_station],352 departure: from_station[:name],353 arrival: to_station[:name],354 departure_time: departure[:departure],355 arrival_time: arrival[:arrival],356 seat_availability: seat_availability,357 seat_fare: fare_information,358 }359 train_search_response_list << train_search_response360 break if train_search_response_list.length >= 10361 end362 end363 content_type :json364 train_search_response_list.to_json365 end366 get '/api/train/seats' do367 date = Time.iso8601(params[:date]).getlocal368 halt_with_error 404, '予約可能期間外です' unless check_available_date(date)369 train = db.xquery(370 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',371 date.strftime('%Y/%m/%d'),372 params[:train_class],373 params[:train_name],374 ).first375 halt_with_error 404, '列車が存在しません' if train.nil?376 from_name = params[:from]377 from_station = db.xquery(378 'SELECT * FROM `station_master` WHERE `name` = ?',379 from_name,380 ).first381 if from_station.nil?382 puts 'fromStation: no rows'383 halt_with_error 400, 'fromStation: no rows'384 end385 to_name = params[:to]386 to_station = db.xquery(387 'SELECT * FROM `station_master` WHERE `name` = ?',388 to_name,389 ).first390 if to_station.nil?391 puts 'toStation: no rows'392 halt_with_error 400, 'toStation: no rows'393 end394 usable_train_class_list = get_usable_train_class_list(from_station, to_station)395 unless usable_train_class_list.include?(train[:train_class])396 puts 'invalid train_class'397 halt_with_error 400, 'invalid train_class'398 end399 seat_list = db.xquery(400 'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? ORDER BY `seat_row`, `seat_column`',401 params[:train_class],402 params[:car_number],403 )404 seat_information_list = []405 seat_list.each do |seat|406 s = {407 row: seat[:seat_row],408 column: seat[:seat_column],409 class: seat[:seat_class],410 is_smoking_seat: seat[:is_smoking_seat],411 is_occupied: false412 }413 query = <<__EOF414 SELECT415 `s`.*416 FROM417 `seat_reservations` `s`,418 `reservations` `r`419 WHERE420 `r`.`date` = ? AND421 `r`.`train_class` = ? AND422 `r`.`train_name` = ? AND423 `car_number` = ? AND424 `seat_row` = ? AND425 `seat_column` = ?426__EOF427 seat_reservation_list = db.xquery(428 query,429 date.strftime('%Y/%m/%d'),430 seat[:train_class],431 params[:train_name],432 seat[:car_number],433 seat[:seat_row],434 seat[:seat_column],435 )436 p seat_reservation_list437 seat_reservation_list.each do |seat_reservation|438 reservation = db.xquery(439 'SELECT * FROM `reservations` WHERE `reservation_id` = ?',440 seat_reservation[:reservation_id],441 ).first442 departure_station = db.xquery(443 'SELECT * FROM `station_master` WHERE `name` = ?',444 reservation[:departure],445 ).first446 arrival_station = db.xquery(447 'SELECT * FROM `station_master` WHERE `name` = ?',448 reservation[:arrival],449 ).first450 if train[:is_nobori]451 # 上り452 if to_station[:id] < arrival_station[:id] && from_station[:id] <= arrival_station[:id]453 # pass454 elsif to_station[:id] >= departure_station[:id] && from_station[:id] > departure_station[:id]455 # pass456 else457 s[:is_occupied] = true458 end459 else460 # 下り461 if from_station[:id] < departure_station[:id] && to_station[:id] <= departure_station[:id]462 # pass463 elsif from_station[:id] >= arrival_station[:id] && to_station[:id] > arrival_station[:id]464 # pass465 else466 s[:is_occupied] = true467 end468 end469 end470 puts s[:is_occupied] ? 'true' : 'false'471 seat_information_list << s472 end473 # 各号車の情報474 simple_car_information_list = []475 i = 1476 loop do477 seat = db.xquery(478 'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? ORDER BY `seat_row`, `seat_column` LIMIT 1',479 params[:train_class],480 i,481 ).first482 break if seat.nil?483 simple_car_information = {484 car_number: i,485 seat_class: seat[:seat_class],486 }487 simple_car_information_list << simple_car_information488 i += 1489 end490 c = {491 date: date.strftime('%Y/%m/%d'),492 train_class: params[:train_class],493 train_name: params[:train_name],494 car_number: params[:car_number].to_i,495 seats: seat_information_list,496 cars: simple_car_information_list,497 }498 content_type :json499 c.to_json500 end501 post '/api/train/reserve' do502 date = Time.iso8601(body_params[:date]).getlocal503 halt_with_error 404, '予約可能期間外です' unless check_available_date(date)504 db.query('BEGIN')505 begin506 tmas = begin507 db.xquery(508 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',509 date.strftime('%Y/%m/%d'),510 body_params[:train_class],511 body_params[:train_name],512 ).first513 rescue Mysql2::Error => e514 db.query('ROLLBACK')515 puts e.message516 halt_with_error 500, '列車データの取得に失敗しました'517 end518 if tmas.nil?519 db.query('ROLLBACK')520 halt_with_error 404, '列車データがみつかりません'521 end522 puts tmas523 # 列車自体の駅IDを求める524 departure_station = begin525 db.xquery(526 'SELECT * FROM `station_master` WHERE `name` = ?',527 tmas[:start_station],528 ).first529 rescue Mysql2::Error => e530 db.query('ROLLBACK')531 puts e.message532 halt_with_error 500, 'リクエストされた列車の始発駅データの取得に失敗しました'533 end534 if departure_station.nil?535 db.query('ROLLBACK')536 halt_with_error 404, 'リクエストされた列車の始発駅データがみつかりません'537 end538 # Arrive539 arrival_station = begin540 db.xquery(541 'SELECT * FROM `station_master` WHERE `name` = ?',542 tmas[:last_station],543 ).first544 rescue Mysql2::Error => e545 db.query('ROLLBACK')546 puts e.message547 halt_with_error 500, 'リクエストされた列車の終着駅データの取得に失敗しました'548 end549 if arrival_station.nil?550 db.query('ROLLBACK')551 halt_with_error 404, 'リクエストされた列車の終着駅データがみつかりません'552 end553 # From554 from_station = begin555 db.xquery(556 'SELECT * FROM `station_master` WHERE `name` = ?',557 body_params[:departure],558 ).first559 rescue Mysql2::Error => e560 db.query('ROLLBACK')561 puts e.message562 halt_with_error 500, '乗車駅データの取得に失敗しました'563 end564 if from_station.nil?565 db.query('ROLLBACK')566 halt_with_error 404, "乗車駅データがみつかりません #{body_params[:departure]}"567 end568 # To569 to_station = begin570 db.xquery(571 'SELECT * FROM `station_master` WHERE `name` = ?',572 body_params[:arrival],573 ).first574 rescue Mysql2::Error => e575 db.query('ROLLBACK')576 puts e.message577 halt_with_error 500, '降車駅駅データの取得に失敗しました'578 end579 if to_station.nil?580 db.query('ROLLBACK')581 halt_with_error 404, "降車駅駅データがみつかりません #{body_params[:arrival]}"582 end583 case body_params[:train_class]584 when '最速'585 if !from_station[:is_stop_express] || !to_station[:is_stop_express]586 db.query('ROLLBACK')587 halt_with_error 400, '最速の止まらない駅です'588 end589 when '中間'590 if !from_station[:is_stop_semi_express] || !to_station[:is_stop_semi_express]591 db.query('ROLLBACK')592 halt_with_error 400, '中間の止まらない駅です'593 end594 when '遅いやつ'595 if !from_station[:is_stop_local] || !to_station[:is_stop_local]596 db.query('ROLLBACK')597 halt_with_error 400, '遅いやつの止まらない駅です'598 end599 else600 db.query('ROLLBACK')601 halt_with_error 400, 'リクエストされた列車クラスが不明です'602 end603 # 運行していない区間を予約していないかチェックする604 if tmas[:is_nobori]605 if from_station[:id] > departure_station[:id] || to_station[:id] > departure_station[:id]606 db.query('ROLLBACK')607 halt_with_error 400, 'リクエストされた区間に列車が運行していない区間が含まれています'608 end609 if arrival_station[:id] >= from_station[:id] || arrival_station[:id] > to_station[:id]610 db.query('ROLLBACK')611 halt_with_error 400, 'リクエストされた区間に列車が運行していない区間が含まれています'612 end613 else614 if from_station[:id] < departure_station[:id] || to_station[:id] < departure_station[:id]615 db.query('ROLLBACK')616 halt_with_error 400, 'リクエストされた区間に列車が運行していない区間が含まれています'617 end618 if arrival_station[:id] <= from_station[:id] || arrival_station[:id] < to_station[:id]619 db.query('ROLLBACK')620 halt_with_error 400, 'リクエストされた区間に列車が運行していない区間が含まれています'621 end622 end623 # あいまい座席検索624 # seatsが空白の時に発動する625 if body_params[:seats].empty?626 if body_params[:seat_class] != 'non-reserved'627 train = begin628 db.xquery(629 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',630 date.strftime('%Y/%m/%d'),631 body_params[:train_class],632 body_params[:train_name],633 ).first634 rescue Mysql2::Error => e635 db.query('ROLLBACK')636 puts e.message637 halt_with_error 400, e.message638 end639 if train.nil?640 db.query('ROLLBACK')641 halt_with_error 404, 'train is not found'642 end643 usable_train_class_list = get_usable_train_class_list(from_station, to_station)644 unless usable_train_class_list.include?(train[:train_class])645 err = 'invalid train_class'646 puts err647 db.query('ROLLBACK')648 halt_with_error 400, err649 end650 body_params[:seats] = [] # 座席リクエスト情報は空に651 (1..16).each do |carnum|652 seat_list = begin653 db.xquery(654 'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? AND `seat_class` = ? AND `is_smoking_seat` = ? ORDER BY `seat_row`, `seat_column`',655 body_params[:train_class],656 carnum,657 body_params[:seat_class],658 !!body_params[:is_smoking_seat],659 )660 rescue Mysql2::Error => e661 db.query('ROLLBACK')662 puts e.message663 halt_with_error 400, e.message664 end665 seat_information_list = []666 seat_list.each do |seat|667 s = {668 row: seat[:seat_row],669 column: seat[:seat_column],670 class: seat[:seat_class],671 is_smoking_seat: seat[:is_smoking_seat],672 is_occupied: false,673 }674 seat_reservation_list = begin675 db.xquery(676 'SELECT `s`.* FROM `seat_reservations` `s`, `reservations` `r` WHERE `r`.`date` = ? AND `r`.`train_class` = ? AND `r`.`train_name` = ? AND `car_number` = ? AND `seat_row` = ? AND `seat_column` = ? FOR UPDATE',677 date.strftime('%Y/%m/%d'),678 seat[:train_class],679 body_params[:train_name],680 seat[:car_number],681 seat[:seat_row],682 seat[:seat_column],683 )684 rescue Mysql2::Error => e685 db.query('ROLLBACK')686 puts e.message687 halt_with_error 400, e.message688 end689 seat_reservation_list.each do |seat_reservation|690 reservation = begin691 db.xquery(692 'SELECT * FROM `reservations` WHERE `reservation_id` = ? FOR UPDATE',693 seat_reservation[:reservation_id],694 ).first695 rescue Mysql2::Error => e696 db.query('ROLLBACK')697 puts e.message698 halt_with_error 400, e.message699 end700 if reservation.nil?701 db.query('ROLLBACK')702 halt_with_error 404, 'reservation is not found'703 end704 departure_station = begin705 db.xquery(706 'SELECT * FROM `station_master` WHERE `name` = ?',707 reservation[:departure],708 ).first709 rescue Mysql2::Error => e710 db.query('ROLLBACK')711 puts e.message712 halt_with_error 400, e.message713 end714 if departure_station.nil?715 db.query('ROLLBACK')716 halt_with_error 404, 'departure_station is not found'717 end718 arrival_station = begin719 db.xquery(720 'SELECT * FROM `station_master` WHERE `name` = ?',721 reservation[:arrival],722 ).first723 rescue Mysql2::Error => e724 db.query('ROLLBACK')725 puts e.message726 halt_with_error 400, e.message727 end728 if arrival_station.nil?729 db.query('ROLLBACK')730 halt_with_error 404, 'arrival_station is not found'731 end732 if train[:is_nobori]733 # 上り734 if to_station[:id] < arrival_station[:id] && from_station[:id] <= arrival_station[:id]735 # pass736 elsif to_station[:id] >= departure_station[:id] && from_station[:id] > departure_station[:id]737 # pass738 else739 s[:is_occupied] = true740 end741 else742 # 下り743 if from_station[:id] < departure_station[:id] && to_station[:id] <= departure_station[:id]744 # pass745 elsif from_station[:id] >= arrival_station[:id] && to_station[:id] > arrival_station[:id]746 # pass747 else748 s[:is_occupied] = true749 end750 end751 end752 seat_information_list << s753 end754 # 曖昧予約席とその他の候補席を選出755 vague_seat = {}756 reserved = false757 vargue = true758 seatnum = body_params[:adult] + body_params[:child] - 1 # 全体の人数からあいまい指定席分を引いておく759 if body_params[:column].nil? || body_params[:column].empty? # A/B/C/D/Eを指定しなければ、空いている適当な指定席を取るあいまいモード760 seatnum = body_params[:adult] + body_params[:child] # あいまい指定せず大人+小人分の座席を取る761 reserved = true # dummy762 vargue = false # dummy763 end764 candidate_seats = []765 # シート分だけ回して予約できる席を検索766 i = 0767 seat_information_list.each do |seat|768 if seat[:column] == body_params[:column] && !seat[:is_occupied] && !reserved && vargue # あいまい席があいてる769 vague_seat = seat770 reserved = true771 elsif !seat[:is_occupied] && i < seatnum # 単に席があいてる772 candidate_seats << {773 row: seat[:row],774 column: seat[:column],775 }776 i += 1777 end778 end779 if vargue && reserved780 body_params[:seats] << vague_seat781 end782 if i > 0783 body_params[:seats].concat(candidate_seats)784 end785 if body_params[:seats].length < body_params[:adult] + body_params[:child]786 # リクエストに対して席数が足りてない787 # 次の号車にうつしたい788 puts '-----------------'789 puts "現在検索中の車両: #{carnum}号車, リクエスト座席数: #{body_params[:adult] + body_params[:child]}, 予約できそうな座席数: #{body_params[:seats].length}, 不足数: #{body_params[:adult] + body_params[:child] - body_params[:seats].length}"790 puts 'リクエストに対して座席数が不足しているため、次の車両を検索します。'791 body_params[:seats] = []792 if carnum == 16793 puts 'この新幹線にまとめて予約できる席数がなかったから検索をやめるよ'794 break795 end796 end797 puts "空き実績: #{carnum}号車 シート: #{body_params[:seats]} 席数: #{body_params[:seats].length}"798 if body_params[:seats].length >= body_params[:adult] + body_params[:child]799 puts '予約情報に追加したよ'800 body_params[:seats] = body_params[:seats][0, body_params[:adult] + body_params[:child]]801 body_params[:car_number] = carnum802 break803 end804 end805 if body_params[:seats].length.zero?806 db.query('ROLLBACK')807 halt_with_error 404, 'あいまい座席予約ができませんでした。指定した席、もしくは1車両内に希望の席数をご用意できませんでした。'808 end809 end810 else811 # 座席情報のValidate812 body_params[:seats].each do |z|813 puts "XXXX #{z}"814 seat_list = begin815 db.xquery(816 'SELECT * FROM `seat_master` WHERE `train_class` = ? AND `car_number` = ? AND `seat_column` = ? AND `seat_row` = ? AND `seat_class` = ?',817 body_params[:train_class],818 body_params[:car_number],819 z[:column],820 z[:row],821 body_params[:seat_class],822 )823 rescue Mysql2::Error => e824 puts e.message825 db.query('ROLLBACK')826 halt_with_error 400, e.message827 end828 if seat_list.to_a.empty?829 db.query('ROLLBACK')830 halt_with_error 404, 'リクエストされた座席情報は存在しません。号車・喫煙席・座席クラスなど組み合わせを見直してください'831 end832 end833 end834 reservations = begin835 db.xquery(836 'SELECT * FROM `reservations` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ? FOR UPDATE',837 date.strftime('%Y/%m/%d'),838 body_params[:train_class],839 body_params[:train_name],840 )841 rescue Mysql2::Error => e842 puts e.message843 db.query('ROLLBACK')844 halt_with_error 500, '列車予約情報の取得に失敗しました'845 end846 reservations.each do |reservation|847 break if body_params[:seat_class] == 'non-reserved'848 # train_masterから列車情報を取得(上り・下りが分かる)849 tmas = begin850 db.xquery(851 'SELECT * FROM `train_master` WHERE `date` = ? AND `train_class` = ? AND `train_name` = ?',852 date.strftime('%Y/%m/%d'),853 body_params[:train_class],854 body_params[:train_name],855 ).first856 rescue Mysql2::Error => e857 puts e.message858 db.query('ROLLBACK')859 halt_with_error 500, '列車データの取得に失敗しました'860 end861 if tmas.nil?862 db.query('ROLLBACK')863 halt_with_error 404, '列車データがみつかりません'864 end865 # 予約情報の乗車区間の駅IDを求める866 # From867 reserved_from_station = begin868 db.xquery(869 'SELECT * FROM `station_master` WHERE `name` = ?',870 reservation[:departure],871 ).first872 rescue Mysql2::Error => e873 puts e.message874 db.query('ROLLBACK')875 halt_with_error 500, '予約情報に記載された列車の乗車駅データの取得に失敗しました'876 end877 if reserved_from_station.nil?878 db.query('ROLLBACK')879 halt_with_error 404, '予約情報に記載された列車の乗車駅データがみつかりません'880 end881 # To882 reserved_to_station = begin883 db.xquery(884 'SELECT * FROM `station_master` WHERE `name` = ?',885 reservation[:arrival],886 ).first887 rescue Mysql2::Error => e888 puts e.message889 db.query('ROLLBACK')890 halt_with_error 500, '予約情報に記載された列車の降車駅データの取得に失敗しました'891 end892 if reserved_to_station.nil?893 db.query('ROLLBACK')894 halt_with_error 404, '予約情報に記載された列車の降車駅データがみつかりません'895 end896 # 予約の区間重複判定897 secdup = false898 if tmas[:is_nobori]899 # 上り900 if to_station[:id] < reserved_to_station[:id] && from_station[:id] <= reserved_to_station[:id]901 # pass902 elsif to_station[:id] >= reserved_from_station[:id] && from_station > reserved_from_station[:id]903 # pass904 else905 secdup = true906 end907 else908 # 下り909 if from_station[:id] < reserved_from_station[:id] && to_station[:id] <= reserved_from_station[:id]910 # pass911 elsif from_station[:id] >= reserved_to_station[:id] && to_station[:id] > reserved_to_station[:id]912 # pass913 else914 secdup = true915 end916 end917 if secdup918 # 区間重複の場合は更に座席の重複をチェックする919 seat_reservations = begin920 db.xquery(921 'SELECT * FROM `seat_reservations` WHERE `reservation_id` = ? FOR UPDATE',922 reservation[:reservation_id],923 )924 rescue Mysql2::Error => e925 puts e.message926 db.query('ROLLBACK')927 halt_with_error 500, '座席予約情報の取得に失敗しました'928 end929 seat_reservations.each do |v|930 body_params[:seats].each do |seat|931 if v[:car_number] == body_params[:car_number] && v[:seat_row] == seat[:row] && v[:seat_column] == seat[:column]932 db.query('ROLLBACK')933 puts "Duplicated #{reservation}"934 halt_with_error 400, 'リクエストに既に予約された席が含まれています'935 end936 end937 end938 end939 end940 # 3段階の予約前チェック終わり941 # 自由席は強制的にSeats情報をダミーにする(自由席なのに席指定予約は不可)942 if body_params[:seat_class] == 'non-reserved'943 body_params[:seats] = []944 body_params[:car_number] = 0945 (body_params[:adult] + body_params[:child]).times do946 body_params[:seats] << {947 row: 0,948 column: '',949 }950 end951 end952 # 運賃計算953 fare = begin954 case body_params[:seat_class]955 when 'premium', 'reserved', 'non-reserved'956 fare_calc(date, from_station[:id], to_station[:id], body_params[:train_class], body_params[:seat_class])957 else958 raise Error, 'リクエストされた座席クラスが不明です'959 end960 rescue Error, ErrorNoRows => e961 db.query('ROLLBACK')962 puts "fareCalc #{e.message}"963 halt_with_error 400, e.message964 end965 sum_fare = (body_params[:adult] * fare) + (body_params[:child] * fare) / 2966 puts 'SUMFARE'967 # userID取得。ログインしてないと怒られる。968 user, status, message = get_user969 if status != 200970 db.query('ROLLBACK')971 puts message972 halt_with_error status, message973 end974 # 予約ID発行と予約情報登録975 begin976 db.xquery(977 'INSERT INTO `reservations` (`user_id`, `date`, `train_class`, `train_name`, `departure`, `arrival`, `status`, `payment_id`, `adult`, `child`, `amount`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',978 user[:id],979 date.strftime('%Y/%m/%d'),980 body_params[:train_class],981 body_params[:train_name],982 body_params[:departure],983 body_params[:arrival],984 'requesting',985 'a',986 body_params[:adult],987 body_params[:child],988 sum_fare,989 )990 rescue Mysql2::Error => e991 db.query('ROLLBACK')992 puts e.message993 halt_with_error 400, "予約の保存に失敗しました。 #{e.message}"994 end995 id = db.last_id # 予約ID996 if id.nil?997 db.query('ROLLBACK')998 halt_with_error 500, '予約IDの取得に失敗しました'999 end1000 # 席の予約情報登録1001 # reservationsレコード1に対してseat_reservationstが1以上登録される1002 body_params[:seats].each do |v|1003 db.xquery(1004 'INSERT INTO `seat_reservations` (`reservation_id`, `car_number`, `seat_row`, `seat_column`) VALUES (?, ?, ?, ?)',1005 id,1006 body_params[:car_number],1007 v[:row],1008 v[:column],1009 )1010 rescue Mysql2::Error => e1011 db.query('ROLLBACK')1012 puts e.message1013 halt_with_error 500, '座席予約の登録に失敗しました'1014 end1015 rescue => e1016 puts e.message1017 db.query('ROLLBACK')1018 halt_with_error 500, e.message1019 end1020 response = {1021 reservation_id: id,1022 amount: sum_fare,1023 is_ok: true1024 }1025 db.query('COMMIT')1026 content_type :json1027 response.to_json1028 end1029 post '/api/train/reservation/commit' do1030 db.query('BEGIN')1031 begin1032 # 予約IDで検索1033 reservation = begin1034 db.xquery(1035 'SELECT * FROM `reservations` WHERE `reservation_id` = ?',1036 body_params[:reservation_id],1037 ).first1038 rescue Mysql2::Error => e1039 db.query('ROLLBACK')1040 puts e.message1041 halt_with_error 500, '予約情報の取得に失敗しました'1042 end1043 if reservation.nil?1044 db.query('ROLLBACK')1045 halt_with_error 404, '予約情報がみつかりません'1046 end1047 # 支払い前のユーザチェック。本人以外のユーザの予約を支払ったりキャンセルできてはいけない。1048 user, status, message = get_user1049 if status != 2001050 db.query('ROLLBACK')1051 puts message1052 halt_with_error status, message1053 end1054 if reservation[:user_id] != user[:id]1055 db.query('ROLLBACK')1056 halt_with_error 403, '他のユーザIDの支払いはできません'1057 end1058 # 予約情報の支払いステータス確認1059 if reservation[:status] == 'done'1060 db.query('ROLLBACK')1061 halt_with_error 403, '既に支払いが完了している予約IDです'1062 end1063 # 決済する1064 pay_info = {1065 card_token: body_params[:card_token],1066 reservation_id: body_params[:reservation_id],1067 amount: reservation[:amount],1068 }1069 payment_api = ENV['PAYMENT_API'] || 'http://payment:5000'1070 uri = URI.parse("#{payment_api}/payment")1071 req = Net::HTTP::Post.new(uri)1072 req.body = {1073 payment_information: pay_info1074 }.to_json1075 req['Content-Type'] = 'application/json'1076 http = Net::HTTP.new(uri.host, uri.port)1077 http.use_ssl = uri.scheme == 'https'1078 res = http.start { http.request(req) }1079 # リクエスト失敗1080 if res.code != '200'1081 db.query('ROLLBACK')1082 puts res.code1083 halt_with_error 500, '決済に失敗しました。カードトークンや支払いIDが間違っている可能性があります'1084 end1085 # リクエスト取り出し1086 output = begin1087 JSON.parse(res.body, symbolize_names: true)1088 rescue JSON::ParserError => e1089 db.query('ROLLBACK')1090 puts e.message1091 halt_with_error 500, 'JSON parseに失敗しました'1092 end1093 # 予約情報の更新1094 begin1095 db.xquery(1096 'UPDATE `reservations` SET `status` = ?, `payment_id` = ? WHERE `reservation_id` = ?',1097 'done',1098 output[:payment_id],1099 body_params[:reservation_id],1100 )1101 rescue Mysql2::Error => e1102 db.query('ROLLBACK')1103 puts e.message1104 halt_with_error 500, '予約情報の更新に失敗しました'1105 end1106 rescue => e1107 puts e.message1108 db.query('ROLLBACK')1109 halt_with_error 500, e.message1110 end1111 rr = {1112 is_ok: true1113 }1114 db.query('COMMIT')1115 content_type :json1116 rr.to_json1117 end1118 get '/api/auth' do1119 user, status, message = get_user1120 if status != 2001121 puts message1122 halt_with_error status, message1123 end1124 content_type :json1125 { email: user[:email] }.to_json1126 end1127 post '/api/auth/signup' do1128 salt = SecureRandom.random_bytes(1024)1129 super_secure_password = OpenSSL::PKCS5.pbkdf2_hmac(1130 body_params[:password],1131 salt,1132 100,1133 256,1134 'sha256',1135 )1136 db.xquery(1137 'INSERT INTO `users` (`email`, `salt`, `super_secure_password`) VALUES (?, ?, ?)',1138 body_params[:email],1139 salt,1140 super_secure_password,1141 )1142 message_response('registration complete')1143 rescue Mysql2::Error => e1144 puts e.message1145 halt_with_error 502, 'user registration failed'1146 end1147 post '/api/auth/login' do1148 user = db.xquery(1149 'SELECT * FROM `users` WHERE `email` = ?',1150 body_params[:email],1151 ).first1152 halt_with_error 403, 'authentication failed' if user.nil?1153 challenge_password = OpenSSL::PKCS5.pbkdf2_hmac(1154 body_params[:password],1155 user[:salt],1156 100,1157 256,1158 'sha256',1159 )1160 halt_with_error 403, 'authentication failed' if user[:super_secure_password] != challenge_password1161 session[:user_id] = user[:id]1162 message_response 'autheticated'1163 end1164 post '/api/auth/logout' do1165 session[:user_id] = 01166 message_response 'logged out'1167 end1168 get '/api/user/reservations' do1169 user, status, message = get_user1170 if status != 2001171 halt_with_error status, message1172 end1173 reservation_list = db.xquery(1174 'SELECT * FROM `reservations` WHERE `user_id` = ?',1175 user[:id],1176 )1177 reservation_response_list = reservation_list.to_a.map do |r|1178 make_reservation_response(r)1179 end1180 content_type :json1181 reservation_response_list.to_json1182 end1183 get '/api/user/reservations/:item_id' do1184 user, status, message = get_user1185 if status != 2001186 halt_with_error status, message1187 end1188 item_id = params[:item_id].to_i1189 if item_id <= 01190 halt_with_error 400, 'incorrect item id'1191 end1192 reservation = db.xquery(1193 'SELECT * FROM `reservations` WHERE `reservation_id` = ? AND `user_id` = ?',1194 item_id,1195 user[:id],1196 ).first1197 halt_with_error 404, 'Reservation not found' if reservation.nil?1198 reservation_response = make_reservation_response(reservation)1199 content_type :json1200 reservation_response.to_json1201 end1202 post '/api/user/reservations/:item_id/cancel' do1203 user, code, message = get_user1204 if code != 2001205 halt_with_error code, message1206 end1207 item_id = params[:item_id].to_i1208 if item_id <= 01209 halt_with_error 400, 'incorrect item id'1210 end1211 db.query('BEGIN')1212 reservation = begin1213 db.xquery(1214 'SELECT * FROM `reservations` WHERE `reservation_id` = ? AND `user_id` = ?',1215 item_id,1216 user[:id],1217 ).first1218 rescue Mysql2::Error => e1219 db.query('ROLLBACK')1220 puts e.message1221 halt_with_error 500, '予約情報の検索に失敗しました'1222 end1223 if reservation.nil?1224 db.query('ROLLBACK')1225 halt_with_error 404, 'reservations naiyo'1226 end1227 case reservation[:status]1228 when 'rejected'1229 db.query('ROLLBACK')1230 halt_with_error 500, '何らかの理由により予約はRejected状態です'1231 when 'done'1232 # 支払いをキャンセルする1233 payment_api = ENV['PAYMENT_API'] || 'http://payment:5000'1234 uri = URI.parse("#{payment_api}/payment/#{reservation[:payment_id]}")1235 req = Net::HTTP::Delete.new(uri)1236 req.body = {1237 payment_id: reservation[:payment_id]1238 }.to_json1239 req['Content-Type'] = 'application/json'1240 http = Net::HTTP.new(uri.host, uri.port)1241 http.use_ssl = uri.scheme == 'https'1242 res = http.start { http.request(req) }1243 # リクエスト失敗1244 if res.code != '200'1245 db.query('ROLLBACK')1246 puts res.code1247 halt_with_error 500, '決済に失敗しました。支払いIDが間違っている可能性があります'1248 end1249 # リクエスト取り出し1250 output = begin1251 JSON.parse(res.body, symbolize_names: true)1252 rescue JSON::ParserError => e1253 db.query('ROLLBACK')1254 puts e.message1255 halt_with_error 500, 'JSON parseに失敗しました'1256 end1257 puts output1258 else1259 # pass1260 end1261 begin1262 db.xquery(1263 'DELETE FROM `reservations` WHERE `reservation_id` = ? AND `user_id` = ?',1264 item_id,1265 user[:id],1266 )1267 rescue Mysql2::Error => e1268 db.query('ROLLBACK')1269 puts e.message1270 halt_with_error 500, e.message1271 end1272 begin1273 db.xquery(1274 'DELETE FROM `seat_reservations` WHERE `reservation_id` = ?',1275 item_id,1276 )1277 rescue Mysql2::Error => e1278 db.query('ROLLBACK')1279 puts e.message1280 halt_with_error 500, e.message1281 end1282 db.query('COMMIT')1283 message_response 'cancell complete'1284 end1285 error do |e|1286 content_type :json1287 { is_error: true, message: e.message }.to_json1288 end1289 end1290end...

Full Screen

Full Screen

ipam_api.rb

Source:ipam_api.rb Github

copy

Full Screen

...44 mac = validate_mac!(params[:mac]) unless mac_param.nil? || mac_param.empty?45 cidr = validate_cidr!(params[:address], params[:prefix])46 group_name = get_request_group(params)47 next_ip = provider.get_next_ip(mac, cidr, group_name)48 halt 404, { error: ERRORS[:no_free_ips] }.to_json if next_ip.nil?49 next_ip.to_json50 rescue Proxy::Validations::Error => e51 logger.warn(e.message)52 halt 400, { error: e.to_s }.to_json53 rescue RuntimeError => e54 logger.warn(e.message)55 halt 500, { error: e.message }.to_json56 rescue Errno::ECONNREFUSED, Errno::ECONNRESET57 logger.warn(ERRORS[:no_connection])58 halt 500, { error: ERRORS[:no_connection] }.to_json59 end60 end61 # Gets the subnet from External IPAM62 #63 # Inputs: 1. address: Network address of the subnet64 # 2. prefix: Network prefix(e.g. 24)65 # 3. group(optional): The name of the External IPAM group66 #67 # Returns:68 # Response if subnet exists:69 # ===========================70 # Http Code: 20071 # JSON Response:72 # {"data": {73 # "id": "33",74 # "subnet": "10.20.30.0",75 # "description": "Subnet description",76 # "mask": "29"}77 # }78 #79 # Response if subnet does not exist:80 # ===========================81 # Http Code: 40482 # JSON Response:83 # {"error": "No subnets found"}84 get '/subnet/:address/:prefix' do85 content_type :json86 begin87 validate_required_params!([:address, :prefix], params)88 cidr = validate_cidr!(params[:address], params[:prefix])89 group_name = get_request_group(params)90 subnet = provider.get_ipam_subnet(cidr, group_name)91 halt 404, { error: ERRORS[:no_subnet] }.to_json if subnet.nil?92 subnet.to_json93 rescue Proxy::Validations::Error => e94 logger.warn(e.message)95 halt 400, { error: e.to_s }.to_json96 rescue RuntimeError => e97 logger.warn(e.message)98 halt 500, { error: e.message }.to_json99 rescue Errno::ECONNREFUSED, Errno::ECONNRESET100 logger.warn(ERRORS[:no_connection])101 halt 500, { error: ERRORS[:no_connection] }.to_json102 end103 end104 # Get a list of groups from External IPAM105 #106 # Returns:107 # Response if success:108 # ===========================109 # Http Code: 200110 # JSON Response:111 # {"data": [112 # {"id": "1", "name": "Group 1", "description": "This is group 1"},113 # {"id": "2", "name": "Group 2", "description": "This is group 2"}114 # ]}115 #116 # Response if no groups exist:117 # ===========================118 # Http Code: 404119 # JSON Response:120 # {"error": "Groups are not supported"}121 #122 # Response if groups are not supported:123 # ===========================124 # Http Code: 500125 # JSON Response:126 # {"error": "Groups are not supported"}127 get '/groups' do128 content_type :json129 begin130 halt 500, { error: ERRORS[:groups_not_supported] }.to_json unless provider.groups_supported?131 groups = provider.get_ipam_groups132 groups.to_json133 rescue Proxy::Validations::Error => e134 logger.warn(e.message)135 halt 400, { error: e.to_s }.to_json136 rescue RuntimeError => e137 logger.warn(e.message)138 halt 500, { error: e.message }.to_json139 rescue Errno::ECONNREFUSED, Errno::ECONNRESET140 logger.warn(ERRORS[:no_connection])141 halt 500, { error: ERRORS[:no_connection] }.to_json142 end143 end144 # Get a group from External IPAM145 #146 # Inputs: 1. group: The name of the External IPAM group147 #148 # Returns:149 # Response if success:150 # ===========================151 # Http Code: 200152 # JSON Response:153 # {"data": {"id": "1", "name": "Group 1", "description": "This is group 1"}}154 #155 # Response if group not found:156 # ===========================157 # Http Code: 404158 # JSON Response:159 # {"error": "Group not Found"}160 #161 # Response if groups are not supported:162 # ===========================163 # Http Code: 500164 # JSON Response:165 # {"error": "Groups are not supported"}166 get '/groups/:group' do167 content_type :json168 begin169 validate_required_params!([:group], params)170 group_name = get_request_group(params)171 group = provider.get_ipam_group(group_name)172 halt 404, { error: ERRORS[:no_group] }.to_json if group.nil?173 group.to_json174 rescue Proxy::Validations::Error => e175 logger.warn(e.message)176 halt 400, { error: e.to_s }.to_json177 rescue RuntimeError => e178 logger.warn(e.message)179 halt 500, { error: e.message }.to_json180 rescue Errno::ECONNREFUSED, Errno::ECONNRESET181 logger.warn(ERRORS[:no_connection])182 halt 500, { error: ERRORS[:no_connection] }.to_json183 end184 end185 # Get a list of subnets for a given External IPAM group186 #187 # Input: 1. group: The name of the External IPAM group188 #189 # Returns:190 # Response if success:191 # ===========================192 # Http Code: 200193 # JSON Response:194 # {"data":[195 # {"subnet":"10.20.30.0","mask":"29","description":"This is a subnet"},196 # {"subnet":"40.50.60.0","mask":"29","description":"This is another subnet"}197 # ]}198 #199 # Response if no subnets exist in group:200 # ===========================201 # Http Code: 404202 # JSON Response:203 # {"error": "No subnets found in External IPAM group"}204 #205 # Response if groups are not supported:206 # ===========================207 # Http Code: 500208 # JSON Response:209 # {"error": "Groups are not supported"}210 get '/groups/:group/subnets' do211 content_type :json212 begin213 validate_required_params!([:group], params)214 group_name = get_request_group(params)215 subnets = provider.get_ipam_subnets(group_name)216 halt 404, { error: ERRORS[:no_subnets_in_group] }.to_json if subnets.nil?217 subnets.to_json218 rescue Proxy::Validations::Error => e219 logger.warn(e.message)220 halt 400, { error: e.to_s }.to_json221 rescue RuntimeError => e222 logger.warn(e.message)223 halt 500, { error: e.message }.to_json224 rescue Errno::ECONNREFUSED, Errno::ECONNRESET225 logger.warn(ERRORS[:no_connection])226 halt 500, { error: ERRORS[:no_connection] }.to_json227 end228 end229 # Checks whether an IP address has already been taken in External IPAM230 #231 # Inputs: 1. address: The network address of the IPv4 or IPv6 subnet.232 # 2. prefix: The subnet prefix(e.g. 24)233 # 3. ip: IP address to be queried234 # 4. group(optional): The name of the External IPAM Group, containing the subnet to check235 #236 # Returns:237 # Response if exists:238 # ===========================239 # Http Code: 200240 # Response: true241 #242 # Response if not exists:243 # ===========================244 # Http Code: 200245 # JSON Response: false246 get '/subnet/:address/:prefix/:ip' do247 content_type :json248 begin249 validate_required_params!([:address, :prefix, :ip], params)250 ip = validate_ip!(params[:ip])251 cidr = validate_cidr!(params[:address], params[:prefix])252 group_name = get_request_group(params)253 subnet = provider.get_ipam_subnet(cidr, group_name)254 halt 404, { error: ERRORS[:no_subnet] }.to_json if subnet.nil?255 validate_ip_in_cidr!(ip, cidr)256 ip_exists = provider.ip_exists?(ip, subnet[:id], group_name)257 halt 200, ip_exists.to_json258 rescue Proxy::Validations::Error => e259 logger.warn(e.message)260 halt 400, { error: e.to_s }.to_json261 rescue RuntimeError => e262 logger.warn(e.message)263 halt 500, { error: e.message }.to_json264 rescue Errno::ECONNREFUSED, Errno::ECONNRESET265 logger.warn(ERRORS[:no_connection])266 halt 500, { error: ERRORS[:no_connection] }.to_json267 end268 end269 # Adds an IP address to the specified subnet for the specified IPAM provider270 #271 # Params: 1. address: The network address of the IPv4 or IPv6 subnet272 # 2. prefix: The subnet prefix(e.g. 24)273 # 3. ip: IP address to be added274 # 4. group(optional): The name of the External IPAM Group, containing the subnet to add ip to275 #276 # Returns:277 # Response if added successfully:278 # ===========================279 # Http Code: 201280 # Response: Empty281 #282 # Response if not added successfully:283 # ===========================284 # Http Code: 500285 # JSON Response:286 # {"error": "Unable to add IP to External IPAM"}287 post '/subnet/:address/:prefix/:ip' do288 content_type :json289 begin290 validate_required_params!([:address, :ip, :prefix], params)291 ip = validate_ip!(params[:ip])292 cidr = validate_cidr!(params[:address], params[:prefix])293 group_name = get_request_group(params)294 subnet = provider.get_ipam_subnet(cidr, group_name)295 halt 404, { error: ERRORS[:no_subnet] }.to_json if subnet.nil?296 add_ip_params = { cidr: cidr, subnet_id: subnet[:id], group_name: group_name }297 validate_ip_in_cidr!(ip, cidr)298 ip_added = provider.add_ip_to_subnet(ip, add_ip_params) # Returns nil on success299 halt 500, ip_added.to_json unless ip_added.nil?300 status 201301 rescue Proxy::Validations::Error => e302 logger.warn(e.message)303 halt 400, { error: e.to_s }.to_json304 rescue RuntimeError => e305 logger.warn(e.message)306 halt 500, { error: e.message }.to_json307 rescue Errno::ECONNREFUSED, Errno::ECONNRESET308 logger.warn(ERRORS[:no_connection])309 halt 500, { error: ERRORS[:no_connection] }.to_json310 end311 end312 # Deletes IP address from a given subnet313 #314 # Params: 1. address: The network address of the IPv4 or IPv6 subnet315 # 2. prefix: The subnet prefix(e.g. 24)316 # 3. ip: IP address to be deleted317 # 4. group(optional): The name of the External IPAM Group, containing the subnet to delete ip from318 #319 # Returns:320 # Response if deleted successfully:321 # ===========================322 # Http Code: 200323 # Response: Empty324 #325 # Response if not added successfully:326 # ===========================327 # Http Code: 500328 # JSON Response:329 # {"error": "Unable to delete IP from External IPAM"}330 delete '/subnet/:address/:prefix/:ip' do331 content_type :json332 begin333 validate_required_params!([:address, :ip, :prefix], params)334 ip = validate_ip!(params[:ip])335 cidr = validate_cidr!(params[:address], params[:prefix])336 group_name = get_request_group(params)337 subnet = provider.get_ipam_subnet(cidr, group_name)338 halt 404, { error: ERRORS[:no_subnet] }.to_json if subnet.nil?339 del_ip_params = { cidr: cidr, subnet_id: subnet[:id], group_name: group_name }340 validate_ip_in_cidr!(ip, cidr)341 ip_deleted = provider.delete_ip_from_subnet(ip, del_ip_params) # Returns nil on success342 halt 500, ip_deleted.to_json unless ip_deleted.nil?343 halt 204344 rescue Proxy::Validations::Error => e345 logger.warn(e.message)346 halt 400, { error: e.to_s }.to_json347 rescue RuntimeError => e348 logger.warn(e.message)349 halt 500, { error: e.message }.to_json350 rescue Errno::ECONNREFUSED, Errno::ECONNRESET351 logger.warn(ERRORS[:no_connection])352 halt 500, { error: ERRORS[:no_connection] }.to_json353 end354 end355 end356end...

Full Screen

Full Screen

requester.rb

Source:requester.rb Github

copy

Full Screen

...11 # Filters out bad requests before performing any routing12 before do13 config = BeEF::Core::Configuration.instance14 # Require a valid API token from a valid IP address15 halt 401 unless params[:token] == config.get('beef.api_token')16 halt 403 unless BeEF::Core::Rest.permitted_source?(request.ip)17 H = BeEF::Core::Models::Http18 HB = BeEF::Core::Models::HookedBrowser19 headers 'Content-Type' => 'application/json; charset=UTF-8',20 'Pragma' => 'no-cache',21 'Cache-Control' => 'no-cache',22 'Expires' => '0'23 end24 # Returns a request by ID25 get '/request/:id' do26 begin27 id = params[:id]28 raise InvalidParamError, 'id' unless BeEF::Filters::nums_only?(id)29 requests = H.find(id)30 halt 404 if requests.nil?31 result = {}32 result[:count] = requests.length33 result[:requests] = []34 requests.each do |request|35 result[:requests] << request2hash(request)36 end37 result.to_json38 rescue InvalidParamError => e39 print_error e.message40 halt 40041 rescue StandardError => e42 print_error "Internal error while retrieving request with id #{id} (#{e.message})"43 halt 50044 end45 end46 # Returns all requestes given a specific hooked browser id47 get '/requests/:id' do48 begin49 id = params[:id]50 raise InvalidParamError, 'id' unless BeEF::Filters.is_valid_hook_session_id?(id)51 requests = H.where(:hooked_browser_id => id)52 halt 404 if requests.nil?53 result = {}54 result[:count] = requests.length55 result[:requests] = []56 requests.each do |request|57 result[:requests] << request2hash(request)58 end59 result.to_json60 rescue InvalidParamError => e61 print_error e.message62 halt 40063 rescue StandardError => e64 print_error "Internal error while retrieving request list for hooked browser with id #{id} (#{e.message})"65 halt 50066 end67 end68 # Return a response by ID69 get '/response/:id' do70 begin71 # super debugging72 error = {}73 error[:code]=074 id = params[:id]75 raise InvalidParamError, 'id' unless BeEF::Filters::nums_only?(id)76 error[:code]=177 responses = H.find(id) || nil78 error[:code]=279 halt 404 if responses.nil?80 error[:code]=381 result = {}82 result[:success] = 'true'83 error[:code]=484 result[:result] = response2hash(responses)85 error[:code]=586 result.to_json87 rescue InvalidParamError => e88 print_error e.message89 halt 40090 rescue StandardError => e91 print_error "Internal error while retrieving response with id #{id} (#{e.message})"92 93 error[:id] = id94 error[:message] = e.message95 error.to_json96 # halt 50097 end98 end99 # Deletes a specific response given its id100 delete '/response/:id' do101 begin102 id = params[:id]103 raise InvalidParamError, 'id' unless BeEF::Filters::nums_only?(id)104 responses = H.find(id) || nil105 halt 404 if responses.nil?106 result = {}107 result['success'] = H.delete(id)108 result.to_json109 rescue InvalidParamError => e110 print_error e.message111 halt 400112 rescue StandardError => e113 print_error "Internal error while removing response with id #{id} (#{e.message})"114 halt 500115 end116 end117 # Send a new HTTP request to the hooked browser118 post '/send/:id' do119 begin120 id = params[:id]121 proto = params[:proto].to_s || 'http'122 raw_request = params['raw_request'].to_s123 zombie = HB.where(:session => id).first || nil124 halt 404 if zombie.nil?125 # @TODO: move most of this to the model126 if raw_request == ''127 raise InvalidParamError, 'raw_request'128 end129 if proto !~ /\Ahttps?\z/130 raise InvalidParamError, 'raw_request: Invalid request URL scheme'131 end132 req_parts = raw_request.split(/ |\n/)133 verb = req_parts[0]134 if not BeEF::Filters.is_valid_verb?(verb)135 raise InvalidParamError, 'raw_request: Only HEAD, GET, POST, OPTIONS, PUT or DELETE requests are supported'136 end137 uri = req_parts[1]138 if not BeEF::Filters.is_valid_url?(uri)139 raise InvalidParamError, 'raw_request: Invalid URI'140 end141 version = req_parts[2]142 if not BeEF::Filters.is_valid_http_version?(version)143 raise InvalidParamError, 'raw_request: Invalid HTTP version'144 end145 host_str = req_parts[3]146 if not BeEF::Filters.is_valid_host_str?(host_str)147 raise InvalidParamError, 'raw_request: Invalid HTTP version'148 end149 # Validate target hsot150 host = req_parts[4]151 host_parts = host.split(/:/)152 host_name = host_parts[0]153 host_port = host_parts[1] || nil154 unless BeEF::Filters.is_valid_hostname?(host_name)155 raise InvalidParamError, 'raw_request: Invalid HTTP HostName'156 end157 host_port = host_parts[1] || nil158 if host_port.nil? || !BeEF::Filters::nums_only?(host_port)159 host_port = proto.eql?('https') ? 443 : 80160 end161 # Save the new HTTP request162 http = H.new(163 :hooked_browser_id => zombie.session,164 :request => raw_request,165 :method => verb,166 :proto => proto,167 :domain => host_name,168 :port => host_port,169 :path => uri,170 :request_date => Time.now,171 :allow_cross_domain => "true",172 )173 print_debug "added new http request for #{zombie.session}"174 print_debug http.to_json175 if verb.eql?('POST') || verb.eql?('PUT')176 req_parts.each_with_index do |value, index|177 if value.match(/^Content-Length/i)178 http.content_length = req_parts[index+1]179 end180 end181 end182 http.save183 result = request2hash(http)184 print_debug "[Requester] Sending HTTP request through zombie [ip: #{zombie.ip}] : #{result}"185 #result.to_json186 rescue InvalidParamError => e187 print_error e.message188 halt 400189 rescue StandardError => e190 print_error "Internal error while removing network host with id #{id} (#{e.message})"191 halt 500192 end193 end194 # Convert a request object to Hash195 def request2hash(http)196 {197 :id => http.id,198 :proto => http.proto,199 :domain => http.domain,200 :port => http.port,201 :path => http.path,202 :has_ran => http.has_ran,203 :method => http.method,204 :request_date => http.request_date,205 :response_date => http.response_date,...

Full Screen

Full Screen

halt

Using AI Code Generation

copy

Full Screen

1 halt 500, {'Content-Type' => 'text/plain'}, 'Something went wrong!'2 throw :halt, [500, {'Content-Type' => 'text/plain'}, 'Something went wrong!']3 throw :halt, [500, {'Content-Type' => 'text/plain'}, ['Something went wrong!']]

Full Screen

Full Screen

halt

Using AI Code Generation

copy

Full Screen

1 halt 500, {'Content-Type' => 'text/plain'}, "Internal Server Error"2 halt [500, {'Content-Type' => 'text/plain'}, "Internal Server Error"]3 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error"]4 halt [500, {'Content-Type' => 'text/plain'}, ["Internal Server Error"]]5 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]6 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]7 halt 500, "Internal Server Error", {'Content-Type' => 'text/plain'}8 halt 500, "Internal Server Error", {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]

Full Screen

Full Screen

halt

Using AI Code Generation

copy

Full Screen

1 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented"2 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"]3 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented", "Not Implemented"]4 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented", "Not Implemented"5 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented", ["Not Implemented"]6 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], "Not Implemented"7 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["Not Implemented"]8 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["Not Implemented"], "Not Implemented"9 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["

Full Screen

Full Screen

halt

Using AI Code Generation

copy

Full Screen

1 halt 500, {'Content-Type' => 'text/plain'}, 'Internal Server Error'2 halt 500, {'Content-Type' => 'text/plain'}, ['Internal Server Error']3 halt 500, {'Content-Type' => 'text/plain'}, 'Internal Server Error'4 halt 500, {'Content-Type' => 'text/plain'}, ['Internal Server Error']5 halt 500, {'Content-Type' => 'text/plain'}, ['Internal Server Error']6 halt 500, {'Content-Type' => 'text/plain'}, 'Internal Server Error'

Full Screen

Full Screen

halt

Using AI Code Generation

copy

Full Screen

1 halt 500, {'Content-Type' => 'text/plain'}, 'Internal Server Error'2 halt 500, {'Content-Type' => 'text/plain'}, ['Internal', ' Server Error']3 halt 500, {'Content-Type' => 'text/plain'}, File.read('500.html')4 halt 500, {'Content-Type' => 'text/plain'}, File.open('500.html')5 halt 500, {'Content-Type' => 'text/plain'}, File.open('500.html', 'r')6 halt 500, {'Content-Type' => 'text/plain'}, File.open('500.html', 'r').read

Full Screen

Full Screen

halt

Using AI Code Generation

copy

Full Screen

1 halt 500, {'Content-Type' => 'text/plain'}, "Internal Server Error"2 halt [500, {'Content-Type' => 'text/plain'}, "Internal Server Error"]3 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error"]4 halt [500, {'Content-Type' => 'text/plain'}, ["Internal Server Error"]]5 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]6 halt 500, {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]7 halt 500, "Internal Server Error", {'Content-Type' => 'text/plain'}8 halt 500, "Internal Server Error", {'Content-Type' => 'text/plain'}, ["Internal Server Error", "Some more content"]

Full Screen

Full Screen

halt

Using AI Code Generation

copy

Full Screen

1 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented"2 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"]3 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented", "Not Implemented"]4 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented", "Not Implemented"5 halt 501, {'Content-Type' => 'text/plain'}, "Not Implemented", ["Not Implemented"]6 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], "Not Implemented"7 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["Not Implemented"]8 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["Not Implemented"], "Not Implemented"9 halt 501, {'Content-Type' => 'text/plain'}, ["Not Implemented"], ["

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful